using IRaCIS.Core.Application.Helper;
using IRaCIS.Core.Application.MassTransit.Command;
using IRaCIS.Core.Application.Service.Reading.Dto;
using IRaCIS.Core.Domain;
using IRaCIS.Core.Domain.BaseModel;
using IRaCIS.Core.Domain.Models;
using IRaCIS.Core.Infra.EFCore.Common;
using MassTransit;
using Microsoft.Extensions.Options;
using MimeKit;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace IRaCIS.Core.Application.MassTransit.Consumer;


/// <summary>
/// CRC 提交了 通知QC进行质控  Code005，006
/// </summary>
public class CRCSubmitedAndQCToAuditEventConsumer(
      IRepository<UserRole> _userRoleRepository,
      IRepository<TrialUserRole> _trialUseRoleRepository,
      IRepository<SubjectVisit> _subjectVisitRepository,
      IRepository<Trial> _trialRepository,
      IRepository<ReadingQuestionCriterionTrial> _readingQuestionCriterionTrialRepository,
      IRepository<VisitTask> _visitTaskRepository,
      IRepository<Dictionary> _dictionaryRepository,
       IRepository<TrialEmailNoticeConfig> _trialEmailNoticeConfigrepository,
      IOptionsMonitor<SystemEmailSendConfig> systemEmailConfig) : IConsumer<CRCSubmitedAndQCToAuditEvent>
{
    private readonly SystemEmailSendConfig _systemEmailConfig = systemEmailConfig.CurrentValue;
    public async Task Consume(ConsumeContext<CRCSubmitedAndQCToAuditEvent> context)
    {
        Log.Logger.Warning("发送(005,006) 【加急项目所有IQC待领取质控任务】邮件！！！");
        var isEn_US = CultureInfo.CurrentCulture.Name == StaticData.CultureInfo.en_US;

        var subjectVisitId = context.Message.SubjectVisitId;

        var subjectVisit = await _subjectVisitRepository.Where(x => x.Id == subjectVisitId).Include(x => x.Subject).FirstNotNullAsync();

        var trialId = subjectVisit.TrialId;

        var scenario = context.Message.IsPd ? EmailBusinessScenario.PDVerification_PendingImageQCClaim : EmailBusinessScenario.EligibilityVerification_PendingClaim;

        var trialEmailConfig = _trialEmailNoticeConfigrepository.Where(t => t.TrialId == trialId && t.BusinessScenarioEnum == scenario && t.IsAutoSend && t.IsEnable).FirstOrDefault();

        var trialUserList = await _trialUseRoleRepository.Where(x => x.TrialId == subjectVisit.TrialId && x.TrialUser.IsDeleted == false)
            .Select(t => new { t.UserRole.IdentityUser.EMail, t.UserRole.FullName, t.UserRole.UserTypeEnum, t.UserRole.IdentityUser.UserWorkLanguage }).ToListAsync();

        var trialInfo = await _trialRepository.FirstOrDefaultAsync(t => t.Id == subjectVisit.TrialId);

        if (trialEmailConfig != null)
        {
            // 遍历语言枚举 在底层判断收件人是否为空，决定是否跳过邮件发送，避免每个邮件场景的地方都重复判断
            foreach (UserWorkLanguage workLanguage in Enum.GetValues<UserWorkLanguage>())
            {
                //重新设置当前发送邮件的语言
                isEn_US = workLanguage == UserWorkLanguage.US;


                var iqcList = trialUserList.Where(x => x.UserTypeEnum == UserTypeEnum.IQC).Where(t => t.UserWorkLanguage == workLanguage).ToList();


                var pmandAPm = trialUserList.Where(x => x.UserTypeEnum == UserTypeEnum.APM || x.UserTypeEnum == UserTypeEnum.ProjectManager).ToList();


                var auditStateCode = "AuditStatePE";

                if (trialInfo.QCProcessEnum == TrialQCProcess.DoubleAudit)
                {
                    auditStateCode = "AuditStateRC";
                }

                var dictionValue = await CommonEmailHelper.TranslationDictionary(new TranslationDictionaryDto()
                {

                    DictionaryRepository = _dictionaryRepository,
                    IsEn_US = isEn_US,
                    DictionaryList = new List<DictionaryDto>()
            {
             new DictionaryDto (){DictionaryCode= auditStateCode,EnumValue=subjectVisit.AuditState.GetEnumInt(), }, //审核状态

            }
                });

                var messageToSend = new MimeMessage();
                //发件地址
                messageToSend.From.Add(new MailboxAddress(_systemEmailConfig.FromName, _systemEmailConfig.FromEmail));


                foreach (var userinfo in iqcList)
                {
                    messageToSend.To.Add(new MailboxAddress(userinfo.FullName, userinfo.EMail));
                }

                var userNames = iqcList.Select(x => x.FullName).ToList();

                foreach (var pm in pmandAPm)
                {
                    messageToSend.Cc.Add(new MailboxAddress(pm.FullName, pm.EMail));
                }

                var companyName = isEn_US ? _systemEmailConfig.CompanyShortName : _systemEmailConfig.CompanyShortNameCN;



                Func<(string topicStr, string htmlBodyStr), (string topicStr, string htmlBodyStr)> emailConfigFunc = input =>
                {
                    var subjectCode = subjectVisit.Subject.Code;
                    var topicStr = string.Format(input.topicStr, trialInfo.ResearchProgramNo, subjectCode, subjectVisit.VisitName);
                    var htmlBodyStr = string.Format(
                       CommonEmailHelper.ReplaceCompanyName(_systemEmailConfig, input.htmlBodyStr, workLanguage),
                       string.Join(',', userNames),  // 用户名  {0}
                       trialInfo.ExperimentName,        // 项目   {1}
                       subjectCode, // 受试者 {2}
                       subjectVisit.VisitName,             // 访视  {3}
                       dictionValue[0],    // 审核状态 {4}
                       _systemEmailConfig.SiteUrl             // 链接                  {5}
                        );

                    return (topicStr, htmlBodyStr);
                };

                await CommonEmailHelper.GetTrialEmailSubejctAndHtmlInfoAndBuildAsync(trialEmailConfig, messageToSend, emailConfigFunc, workLanguage);

                await SendEmailHelper.SendTrialEmailAsync(messageToSend, trialInfo);


            }


        }

    }
}


/// <summary>
/// CRC 回复质控质疑 通知QC  Code012，013
/// </summary>
public class CRCRepliedQCChallengeEventConsumer(
      IRepository<UserRole> _userRoleRepository,
        IRepository<TrialUserRole> _trialUseRoleRepository,
       IRepository<SubjectVisit> _subjectVisitRepository,
      IRepository<Trial> _trialRepository,
      IRepository<QCChallenge> _qCChallengeRepository,
      IRepository<QCChallengeDialog> _qCChallengeDialogRepository,
         IRepository<Dictionary> _dictionaryRepository,
       IRepository<TrialEmailNoticeConfig> _trialEmailNoticeConfigrepository,
      IOptionsMonitor<SystemEmailSendConfig> systemEmailConfig) : IConsumer<CRCRepliedQCChallengeEvent>
{

    private readonly SystemEmailSendConfig _systemEmailConfig = systemEmailConfig.CurrentValue;
    public async Task Consume(ConsumeContext<CRCRepliedQCChallengeEvent> context)
    {
        Log.Logger.Warning("发送(Code012，013) 【CRC 回复质控质疑 通知QC】邮件！！！");
        var isEn_US = CultureInfo.CurrentCulture.Name == StaticData.CultureInfo.en_US;

        var subjectVisitId = context.Message.SubjectVisitId;

        var subjectVisit = await _subjectVisitRepository.Where(x => x.Id == subjectVisitId).Include(x => x.Subject).Include(x => x.CurrentActionUser).FirstNotNullAsync();

        var trialId = subjectVisit.TrialId;

        var scenario = context.Message.IsPd ? EmailBusinessScenario.PDVerification_UnderQCQuery : EmailBusinessScenario.EligibilityVerification_Pending;



        var trialEmailConfig = _trialEmailNoticeConfigrepository.Where(t => t.TrialId == trialId && t.BusinessScenarioEnum == scenario && t.IsAutoSend && t.IsEnable).FirstOrDefault();

        if (trialEmailConfig != null)
        {
            var qCChallengeDialog = await _qCChallengeDialogRepository.Where(x => x.Id == context.Message.QCChallengeDialogId).Include(x => x.QCChallenge).FirstNotNullAsync();

            var trialUserList = await _trialUseRoleRepository.Where(x => x.TrialId == subjectVisit.TrialId && x.TrialUser.IsDeleted == false)
                .Select(t => new { t.UserRole.IdentityUser.EMail, t.UserRole.FullName, t.UserRole.UserTypeEnum, t.UserRole.IdentityUser.UserWorkLanguage }).ToListAsync();


            var userinfoList = trialUserList.Where(x => x.UserTypeEnum == UserTypeEnum.IQC).ToList();
            var pmandAPm = trialUserList.Where(x => x.UserTypeEnum == UserTypeEnum.APM || x.UserTypeEnum == UserTypeEnum.ProjectManager).ToList();
            var trialInfo = await _trialRepository.FirstOrDefaultAsync(t => t.Id == subjectVisit.TrialId);


            var userinfo = subjectVisit.CurrentActionUser;

            //重新设置当前发送邮件的语言
            var workLanguage = _userRoleRepository.Where(t => t.Id == userinfo.Id).Select(t => t.IdentityUser.UserWorkLanguage).First();
            isEn_US = workLanguage == UserWorkLanguage.US;

            var messageToSend = new MimeMessage();
            //发件地址
            messageToSend.From.Add(new MailboxAddress(_systemEmailConfig.FromName, _systemEmailConfig.FromEmail));
            messageToSend.To.Add(new MailboxAddress(userinfo.FullName, userinfo.EMail));

            foreach (var pm in pmandAPm)
            {
                messageToSend.Cc.Add(new MailboxAddress(pm.FullName, pm.EMail));
            }
            var companyName = isEn_US ? _systemEmailConfig.CompanyShortName : _systemEmailConfig.CompanyShortNameCN;


            var dictionValue = await CommonEmailHelper.TranslationDictionary(new TranslationDictionaryDto()
            {

                DictionaryRepository = _dictionaryRepository,
                IsEn_US = isEn_US,
                DictionaryList = new List<DictionaryDto>()
            {
             new DictionaryDto (){DictionaryCode= "YesOrNo",EnumValue=qCChallengeDialog.QCChallenge.IsClosed.ToString().ToLower(), }, //是否关闭

            }
            });

            Func<(string topicStr, string htmlBodyStr), (string topicStr, string htmlBodyStr)> emailConfigFunc = input =>
            {
                var subjectCode = subjectVisit.Subject.Code;
                var topicStr = string.Format(input.topicStr, trialInfo.ResearchProgramNo, subjectCode, subjectVisit.VisitName);
                var htmlBodyStr = string.Format(
                   CommonEmailHelper.ReplaceCompanyName(_systemEmailConfig, input.htmlBodyStr, workLanguage),
                   userinfo.FullName,              // 用户名  {0}
                   trialInfo.ExperimentName,        // 项目   {1}
                   subjectCode, // 受试者 {2}
                   subjectVisit.VisitName,             // 访视  {3}
                   dictionValue[0],    // 是否关闭 {4}
                   qCChallengeDialog.TalkContent,    // 质疑内容{5}
                   _systemEmailConfig.SiteUrl             // 链接                  {6}
                    );

                return (topicStr, htmlBodyStr);
            };
            await CommonEmailHelper.GetTrialEmailSubejctAndHtmlInfoAndBuildAsync(trialEmailConfig, messageToSend, emailConfigFunc, workLanguage);

            await SendEmailHelper.SendTrialEmailAsync(messageToSend, trialInfo);
        }
    }
}


/// <summary>
/// QC回复 质控质疑，通知CRC (014，015)
/// </summary>
public class QCRepliedQCChallengeEventConsumer(
      IRepository<UserRole> _userRoleRepository,
        IRepository<TrialUserRole> _trialUseRoleRepository,
       IRepository<SubjectVisit> _subjectVisitRepository,
      IRepository<Trial> _trialRepository,
      IRepository<QCChallenge> _qCChallengeRepository,
      IRepository<QCChallengeDialog> _qCChallengeDialogRepository,
         IRepository<Dictionary> _dictionaryRepository,
       IRepository<TrialEmailNoticeConfig> _trialEmailNoticeConfigrepository,
      IOptionsMonitor<SystemEmailSendConfig> systemEmailConfig) : IConsumer<QCRepliedQCChallengeEvent>
{
    private readonly SystemEmailSendConfig _systemEmailConfig = systemEmailConfig.CurrentValue;
    public async Task Consume(ConsumeContext<QCRepliedQCChallengeEvent> context)
    {
        Log.Logger.Warning("发送(014，015) 【  QC回复 质控质疑，通知CRC】邮件！！！");
        var isEn_US = CultureInfo.CurrentCulture.Name == StaticData.CultureInfo.en_US;

        var subjectVisitId = context.Message.SubjectVisitId;

        var subjectVisit = await _subjectVisitRepository.Where(x => x.Id == subjectVisitId).Include(x => x.Subject).FirstNotNullAsync();

        var trialId = subjectVisit.TrialId;

        var scenario = context.Message.IsPd ? EmailBusinessScenario.PDVerification_ImageQuery : EmailBusinessScenario.EligibilityVerification_ImageQuery;

        var trialEmailConfig = _trialEmailNoticeConfigrepository.Where(t => t.TrialId == trialId && t.BusinessScenarioEnum == scenario && t.IsAutoSend && t.IsEnable).FirstOrDefault();

        if (trialEmailConfig != null)
        {


            string talkContent = string.Empty;
            var isclose = false;
            if (context.Message.QCChallengeDialogId != null)
            {
                var qCChallengeDialog = await _qCChallengeDialogRepository.Where(x => x.Id == context.Message.QCChallengeDialogId.Value).Include(x => x.QCChallenge).FirstNotNullAsync();
                talkContent = qCChallengeDialog.TalkContent;
                isclose = qCChallengeDialog.QCChallenge.IsClosed;
            }
            else if (context.Message.QCChallengeId != null)
            {
                var qCChallenge = await _qCChallengeRepository.Where(x => x.Id == context.Message.QCChallengeId.Value).FirstNotNullAsync();
                talkContent = qCChallenge.Content;
                isclose = qCChallenge.IsClosed;
            }


            var trialUserList = await _trialUseRoleRepository.Where(x => x.TrialId == subjectVisit.TrialId && x.TrialUser.IsDeleted == false)
            .Select(t => new { t.UserRole.IdentityUser.EMail, t.UserRole.FullName, t.UserRole.UserTypeEnum, t.UserRole.IdentityUser.UserWorkLanguage }).ToListAsync();

            var trialInfo = await _trialRepository.FirstOrDefaultAsync(t => t.Id == subjectVisit.TrialId);


            // 遍历语言枚举 在底层判断收件人是否为空，决定是否跳过邮件发送，避免每个邮件场景的地方都重复判断
            foreach (UserWorkLanguage workLanguage in Enum.GetValues<UserWorkLanguage>())
            {
                //重新设置当前发送邮件的语言
                isEn_US = workLanguage == UserWorkLanguage.US;


                var userinfoList = trialUserList.Where(x => x.UserTypeEnum == UserTypeEnum.ClinicalResearchCoordinator).Where(t => t.UserWorkLanguage == workLanguage).ToList();

                var craInfoList = trialUserList.Where(x => x.UserTypeEnum == UserTypeEnum.CRA).ToList();

                var dictionValue = await CommonEmailHelper.TranslationDictionary(new TranslationDictionaryDto()
                {

                    DictionaryRepository = _dictionaryRepository,
                    IsEn_US = isEn_US,
                    DictionaryList = new List<DictionaryDto>()
                    {
                  new DictionaryDto (){DictionaryCode= "YesOrNo",EnumValue=isclose.ToString().ToLower(), }, //是否关闭

                 }
                });


                var messageToSend = new MimeMessage();
                //发件地址
                messageToSend.From.Add(new MailboxAddress(_systemEmailConfig.FromName, _systemEmailConfig.FromEmail));

                var toUserName = string.Join('、', userinfoList.Select(t => t.FullName));

                foreach (var userinfo in userinfoList)
                {
                    messageToSend.To.Add(new MailboxAddress(userinfo.FullName, userinfo.EMail));
                }

                foreach (var user in craInfoList)
                {
                    messageToSend.Cc.Add(new MailboxAddress(user.FullName, user.EMail));
                }

                var companyName = isEn_US ? _systemEmailConfig.CompanyShortName : _systemEmailConfig.CompanyShortNameCN;

                Func<(string topicStr, string htmlBodyStr), (string topicStr, string htmlBodyStr)> emailConfigFunc = input =>
                {
                    var subjectCode = subjectVisit.Subject.Code;
                    var topicStr = string.Format(input.topicStr, trialInfo.ResearchProgramNo, subjectCode, subjectVisit.VisitName);
                    var htmlBodyStr = string.Format(
                       CommonEmailHelper.ReplaceCompanyName(_systemEmailConfig, input.htmlBodyStr, workLanguage),
                       toUserName,              // 用户名  {0}
                       trialInfo.ExperimentName,        // 项目   {1}
                       subjectCode, // 受试者 {2}
                       subjectVisit.VisitName,             // 访视  {3}
                       dictionValue[0],    // 质疑是否关闭 {4}
                       talkContent,    // 质疑内容 {5}
                       _systemEmailConfig.SiteUrl             // 链接                  {65}
                        );

                    return (topicStr, htmlBodyStr);
                };


                await CommonEmailHelper.GetTrialEmailSubejctAndHtmlInfoAndBuildAsync(trialEmailConfig, messageToSend, emailConfigFunc, workLanguage);

                await SendEmailHelper.SendTrialEmailAsync(messageToSend, trialInfo);

            }


        }
    }
}


/// <summary>
/// CRC 回复一致性核查质疑 通知PM  (019,020)
/// </summary>
public class CRCRepliedCheckChallengeEventConsumer(
      IRepository<UserRole> _userRoleRepository,
        IRepository<TrialUserRole> _trialUseRoleRepository,
       IRepository<SubjectVisit> _subjectVisitRepository,
      IRepository<Trial> _trialRepository,
      IRepository<QCChallenge> _qCChallengeRepository,
      IRepository<QCChallengeDialog> _qCChallengeDialogRepository,
         IRepository<Dictionary> _dictionaryRepository,
       IRepository<TrialEmailNoticeConfig> _trialEmailNoticeConfigrepository,
      IOptionsMonitor<SystemEmailSendConfig> systemEmailConfig) : IConsumer<CRCRepliedCheckChallengeEvent>
{

    private readonly SystemEmailSendConfig _systemEmailConfig = systemEmailConfig.CurrentValue;
    public async Task Consume(ConsumeContext<CRCRepliedCheckChallengeEvent> context)
    {
        Log.Logger.Warning("发送(019,020) 【 CRC 回复一致性核查质疑 通知PM】邮件！！！");
        var isEn_US = CultureInfo.CurrentCulture.Name == StaticData.CultureInfo.en_US;



        var subjectVisitId = context.Message.SubjectVisitId;

        var subjectVisit = await _subjectVisitRepository.Where(x => x.Id == subjectVisitId).Include(x => x.Subject).FirstNotNullAsync();

        var trialId = subjectVisit.TrialId;

        var scenario = context.Message.IsPd ? EmailBusinessScenario.PDVerification_UnderDRForPMOrAPM : EmailBusinessScenario.EligibilityVerification_UnderDRForPMOrAPM;

        var trialEmailConfig = _trialEmailNoticeConfigrepository.Where(t => t.TrialId == trialId && t.BusinessScenarioEnum == scenario && t.IsAutoSend && t.IsEnable).FirstOrDefault();

        if (trialEmailConfig != null)
        {


            var trialUserList = await _trialUseRoleRepository.Where(x => x.TrialId == subjectVisit.TrialId && x.TrialUser.IsDeleted == false)
               .Select(t => new { t.UserRole.IdentityUser.EMail, t.UserRole.FullName, t.UserRole.UserTypeEnum, t.UserRole.IdentityUser.UserWorkLanguage }).ToListAsync();



            var trialInfo = await _trialRepository.FirstOrDefaultAsync(t => t.Id == subjectVisit.TrialId);

            // 遍历语言枚举 在底层判断收件人是否为空，决定是否跳过邮件发送，避免每个邮件场景的地方都重复判断
            foreach (UserWorkLanguage workLanguage in Enum.GetValues<UserWorkLanguage>())
            {
                //重新设置当前发送邮件的语言
                isEn_US = workLanguage == UserWorkLanguage.US;



                var dictionValue = await CommonEmailHelper.TranslationDictionary(new TranslationDictionaryDto()
                {

                    DictionaryRepository = _dictionaryRepository,
                    IsEn_US = isEn_US,
                    DictionaryList = new List<DictionaryDto>()
                     {
                      new DictionaryDto (){DictionaryCode= "CheckState",EnumValue=subjectVisit.CheckState.GetEnumInt(), }, //审核状态

                     }
                });

                var userinfoList = trialUserList.Where(x => x.UserTypeEnum == UserTypeEnum.APM || x.UserTypeEnum == UserTypeEnum.ProjectManager)
                    .Where(t => t.UserWorkLanguage == workLanguage).ToList();


                var messageToSend = new MimeMessage();

                //发件地址
                messageToSend.From.Add(new MailboxAddress(_systemEmailConfig.FromName, _systemEmailConfig.FromEmail));

                var toUserName = string.Join('、', userinfoList.Select(t => t.FullName));
                foreach (var userinfo in userinfoList)
                {
                    messageToSend.To.Add(new MailboxAddress(userinfo.FullName, userinfo.EMail));
                }

                var companyName = isEn_US ? _systemEmailConfig.CompanyShortName : _systemEmailConfig.CompanyShortNameCN;


                Func<(string topicStr, string htmlBodyStr), (string topicStr, string htmlBodyStr)> emailConfigFunc = input =>
                {
                    var subjectCode = subjectVisit.Subject.Code;
                    var topicStr = string.Format(input.topicStr, trialInfo.ResearchProgramNo, subjectCode, subjectVisit.VisitName);
                    var htmlBodyStr = string.Format(
                       CommonEmailHelper.ReplaceCompanyName(_systemEmailConfig, input.htmlBodyStr, workLanguage),
                       toUserName,              // 用户名  {0}
                       trialInfo.ExperimentName,        // 项目   {1}
                       subjectCode, // 受试者 {2}
                       subjectVisit.VisitName,             // 访视  {3}
                       dictionValue[0],    // 核查状态 {4}
                       _systemEmailConfig.SiteUrl             // 链接                  {5}
                        );

                    return (topicStr, htmlBodyStr);
                };


                await CommonEmailHelper.GetTrialEmailSubejctAndHtmlInfoAndBuildAsync(trialEmailConfig, messageToSend, emailConfigFunc, workLanguage);

                await SendEmailHelper.SendTrialEmailAsync(messageToSend, trialInfo);

            }






        }
    }
}



/// <summary>
/// PM 一致性核查 通知CRC (016，017)

/// </summary>
public class PMRepliedCheckChallengeEventConsumer(
      IRepository<UserRole> _userRoleRepository,
        IRepository<TrialUserRole> _trialUseRoleRepository,
       IRepository<SubjectVisit> _subjectVisitRepository,
      IRepository<Trial> _trialRepository,
      IRepository<CheckChallengeDialog> _checkChallengeDialogRepository,
      IRepository<QCChallengeDialog> _qCChallengeDialogRepository,
         IRepository<Dictionary> _dictionaryRepository,
       IRepository<TrialEmailNoticeConfig> _trialEmailNoticeConfigrepository,
      IOptionsMonitor<SystemEmailSendConfig> systemEmailConfig) : IConsumer<PMRepliedCheckChallengeEvent>
{

    private readonly SystemEmailSendConfig _systemEmailConfig = systemEmailConfig.CurrentValue;
    public async Task Consume(ConsumeContext<PMRepliedCheckChallengeEvent> context)
    {
        Log.Logger.Warning("发送(016，017) 【  PM 一致性核查 通知CRC】邮件！！！");
        var isEn_US = CultureInfo.CurrentCulture.Name == StaticData.CultureInfo.en_US;

        var subjectVisitId = context.Message.SubjectVisitId;

        var subjectVisit = await _subjectVisitRepository.Where(x => x.Id == subjectVisitId).Include(x => x.NoneDicomStudyList).Include(x => x.StudyList).Include(x => x.Subject).Include(t => t.TrialSite).FirstNotNullAsync();

        var trialId = subjectVisit.TrialId;


        var scenario = context.Message.IsPd ? EmailBusinessScenario.PDVerification_UnderDR : EmailBusinessScenario.EligibilityVerification_UnderDR;

        var trialEmailConfig = _trialEmailNoticeConfigrepository.Where(t => t.TrialId == trialId && t.BusinessScenarioEnum == scenario && t.IsAutoSend && t.IsEnable).FirstOrDefault();

        if (trialEmailConfig != null)
        {

            var checkChallengeDialog = await _checkChallengeDialogRepository.Where(x => x.Id == context.Message.CheckChallengeDialogId).FirstNotNullAsync();


            var trialUserList = await _trialUseRoleRepository.Where(x => x.TrialId == subjectVisit.TrialId && x.TrialUser.IsDeleted == false)
                .Select(t => new { t.UserRole.IdentityUser.EMail, t.UserRole.FullName, t.UserRole.UserTypeEnum, t.UserRole.IdentityUser.UserWorkLanguage }).ToListAsync();


            var craInfoList = trialUserList.Where(x => x.UserTypeEnum == UserTypeEnum.CRA).ToList();

            var trialInfo = await _trialRepository.FirstOrDefaultAsync(t => t.Id == subjectVisit.TrialId);


            List<string> modalities = new List<string>();
            modalities = subjectVisit.NoneDicomStudyList.Select(t => t.Modality)
     .Union(subjectVisit.StudyList.Select(k => k.ModalityForEdit)).ToList();



            // 遍历语言枚举 在底层判断收件人是否为空，决定是否跳过邮件发送，避免每个邮件场景的地方都重复判断
            //foreach (UserWorkLanguage workLanguage in Enum.GetValues<UserWorkLanguage>())
            {
                //重新设置当前发送邮件的语言

                isEn_US = subjectVisit.TrialSite.Country == StaticData.SiteCountry.US;

                var workLanguage = isEn_US ? UserWorkLanguage.US : UserWorkLanguage.CN;

                var userinfoList = trialUserList.Where(x => x.UserTypeEnum == UserTypeEnum.ClinicalResearchCoordinator).Where(t => t.UserWorkLanguage == workLanguage).ToList();


                var dictionValue = await CommonEmailHelper.TranslationDictionary(new TranslationDictionaryDto()
                {

                    DictionaryRepository = _dictionaryRepository,
                    IsEn_US = isEn_US,
                    DictionaryList = new List<DictionaryDto>()
                 {
                    new DictionaryDto (){DictionaryCode= "CheckState",EnumValue=subjectVisit.CheckState.GetEnumInt(), }, //核查状态

                 }
                });

                var messageToSend = new MimeMessage();

                //发件地址
                messageToSend.From.Add(new MailboxAddress(_systemEmailConfig.FromName, _systemEmailConfig.FromEmail));

                var toUserName = string.Join('、', userinfoList.Select(t => t.FullName));
                foreach (var userinfo in userinfoList)
                {
                    messageToSend.To.Add(new MailboxAddress(userinfo.FullName, userinfo.EMail));
                }

                foreach (var user in craInfoList)
                {
                    messageToSend.Cc.Add(new MailboxAddress(user.FullName, user.EMail));
                }

                var companyName = isEn_US ? _systemEmailConfig.CompanyShortName : _systemEmailConfig.CompanyShortNameCN;


                Func<(string topicStr, string htmlBodyStr), (string topicStr, string htmlBodyStr)> emailConfigFunc = input =>
                {
                    var subjectCode = subjectVisit.Subject.Code;
                    var topicStr = string.Format(input.topicStr, trialInfo.ResearchProgramNo, subjectCode, subjectVisit.VisitName);
                    var htmlBodyStr = string.Format(
                       CommonEmailHelper.ReplaceCompanyName(_systemEmailConfig, input.htmlBodyStr, workLanguage),
                       toUserName,              // 用户名  {0}
                       trialInfo.ExperimentName,        // 项目   {1}

                       subjectCode, // 受试者 {2}
                       subjectVisit.VisitName,             // 访视  {3}
                      string.Join(',', modalities),    // 检查类型 {4}
                       dictionValue[0],    // 核查状态 {5}
                       checkChallengeDialog.TalkContent,// 质疑内容{6}
                       _systemEmailConfig.SiteUrl             // 链接                  {7}
                        );

                    return (topicStr, htmlBodyStr);
                };


                await CommonEmailHelper.GetTrialEmailSubejctAndHtmlInfoAndBuildAsync(trialEmailConfig, messageToSend, emailConfigFunc, workLanguage);

                await SendEmailHelper.SendTrialEmailAsync(messageToSend, trialInfo);
            }

        }
    }
}


/// <summary>
/// 通知PM 进行一致性核查 (018,030)
/// </summary>
public class CheckStateChangedToAuditEventConsumer(
      IRepository<UserRole> _userRoleRepository,
        IRepository<TrialUserRole> _trialUseRoleRepository,
       IRepository<SubjectVisit> _subjectVisitRepository,
      IRepository<Trial> _trialRepository,
      IRepository<QCChallenge> _qCChallengeRepository,
      IRepository<QCChallengeDialog> _qCChallengeDialogRepository,
         IRepository<Dictionary> _dictionaryRepository,
       IRepository<TrialEmailNoticeConfig> _trialEmailNoticeConfigrepository,
      IOptionsMonitor<SystemEmailSendConfig> systemEmailConfig) : IConsumer<CheckStateChangedToAuditEvent>
{
    private readonly SystemEmailSendConfig _systemEmailConfig = systemEmailConfig.CurrentValue;
    public async Task Consume(ConsumeContext<CheckStateChangedToAuditEvent> context)
    {
        Console.WriteLine("发送(018,030) 【通知PM 进行一致性核查】邮件！！！");
        var isEn_US = CultureInfo.CurrentCulture.Name == StaticData.CultureInfo.en_US;


        var subjectVisitId = context.Message.SubjectVisitId;

        var subjectVisit = await _subjectVisitRepository.Where(x => x.Id == subjectVisitId).Include(x => x.Subject).FirstNotNullAsync();

        var trialId = subjectVisit.TrialId;

        var scenario = context.Message.IsPd ? EmailBusinessScenario.PDVerification_DR : EmailBusinessScenario.EligibilityVerification_DR;

        var trialEmailConfig = _trialEmailNoticeConfigrepository.Where(t => t.TrialId == trialId && t.BusinessScenarioEnum == scenario && t.IsAutoSend && t.IsEnable).FirstOrDefault();

        if (trialEmailConfig != null)
        {



            var trialUserList = await _trialUseRoleRepository.Where(x => x.TrialId == subjectVisit.TrialId && x.TrialUser.IsDeleted == false)
                 .Select(t => new { t.UserRole.IdentityUser.EMail, t.UserRole.FullName, t.UserRole.UserTypeEnum, t.UserRole.IdentityUser.UserWorkLanguage }).ToListAsync();



            var trialInfo = await _trialRepository.FirstOrDefaultAsync(t => t.Id == subjectVisit.TrialId);


            // 遍历语言枚举 在底层判断收件人是否为空，决定是否跳过邮件发送，避免每个邮件场景的地方都重复判断
            foreach (UserWorkLanguage workLanguage in Enum.GetValues<UserWorkLanguage>())
            {
                //重新设置当前发送邮件的语言
                isEn_US = workLanguage == UserWorkLanguage.US;

                var userinfoList = trialUserList.Where(x => x.UserTypeEnum == UserTypeEnum.APM || x.UserTypeEnum == UserTypeEnum.ProjectManager)
                    .Where(t => t.UserWorkLanguage == workLanguage).ToList();

                var dictionValue = await CommonEmailHelper.TranslationDictionary(new TranslationDictionaryDto()
                {

                    DictionaryRepository = _dictionaryRepository,
                    IsEn_US = isEn_US,
                    DictionaryList = new List<DictionaryDto>()
                {
                 new DictionaryDto (){DictionaryCode= "CheckState",EnumValue=subjectVisit.CheckState.GetEnumInt(), }, //审核状态

                }
                });


                var messageToSend = new MimeMessage();
                //发件地址
                messageToSend.From.Add(new MailboxAddress(_systemEmailConfig.FromName, _systemEmailConfig.FromEmail));

                var toUserName = string.Join('、', userinfoList.Select(t => t.FullName));

                foreach (var userinfo in userinfoList)
                {
                    messageToSend.To.Add(new MailboxAddress(userinfo.FullName, userinfo.EMail));
                }


                var companyName = isEn_US ? _systemEmailConfig.CompanyShortName : _systemEmailConfig.CompanyShortNameCN;

                Func<(string topicStr, string htmlBodyStr), (string topicStr, string htmlBodyStr)> emailConfigFunc = input =>
                {
                    var subjectCode = subjectVisit.Subject.Code;
                    var topicStr = string.Format(input.topicStr, trialInfo.ResearchProgramNo, subjectCode, subjectVisit.VisitName);
                    var htmlBodyStr = string.Format(
                       CommonEmailHelper.ReplaceCompanyName(_systemEmailConfig, input.htmlBodyStr, workLanguage),
                        toUserName,   // 姓名  {0}
                        trialInfo.ExperimentName,        // 项目   {1}                       
                       subjectCode, // 受试者 {2}
                       subjectVisit.VisitName,             // 访视  {3}
                       dictionValue[0],    // 核查状态 {4}
                       _systemEmailConfig.SiteUrl             // 链接                  {5}
                        );

                    return (topicStr, htmlBodyStr);
                };


                await CommonEmailHelper.GetTrialEmailSubejctAndHtmlInfoAndBuildAsync(trialEmailConfig, messageToSend, emailConfigFunc, workLanguage);

                await SendEmailHelper.SendTrialEmailAsync(messageToSend, trialInfo);
            }

        }
    }
}

/// <summary>
/// QC 领取了质控任务 (007，008) 
/// </summary>
public class QCClaimTaskEventConsumer(
      IRepository<UserRole> _userRoleRepository,
        IRepository<TrialUserRole> _trialUseRoleRepository,
       IRepository<SubjectVisit> _subjectVisitRepository,
      IRepository<Trial> _trialRepository,
      IRepository<QCChallenge> _qCChallengeRepository,
      IRepository<QCChallengeDialog> _qCChallengeDialogRepository,
         IRepository<Dictionary> _dictionaryRepository,
       IRepository<TrialEmailNoticeConfig> _trialEmailNoticeConfigrepository,
      IOptionsMonitor<SystemEmailSendConfig> systemEmailConfig) : IConsumer<QCClaimTaskEvent>
{
    private readonly SystemEmailSendConfig _systemEmailConfig = systemEmailConfig.CurrentValue;
    public async Task Consume(ConsumeContext<QCClaimTaskEvent> context)
    {
        Log.Logger.Warning("发送(Code007，008) 【QC 领取了质控任务】邮件！！！");
        var isEn_US = CultureInfo.CurrentCulture.Name == StaticData.CultureInfo.en_US;



        var subjectVisitId = context.Message.SubjectVisitId;

        var subjectVisit = await _subjectVisitRepository.Where(x => x.Id == subjectVisitId).Include(x => x.Subject).Include(x => x.CurrentActionUser).FirstNotNullAsync();

        var trialId = subjectVisit.TrialId;

        var scenario = context.Message.IsPd ? EmailBusinessScenario.PDVerification_PendingImageQC : EmailBusinessScenario.EligibilityVerification_PendingImageQC;

        var trialEmailConfig = _trialEmailNoticeConfigrepository.Where(t => t.TrialId == trialId && t.BusinessScenarioEnum == scenario && t.IsAutoSend && t.IsEnable).FirstOrDefault();

        if (trialEmailConfig != null)
        {


            var subjectVisitList = await _subjectVisitRepository.Where(x => x.CurrentActionUserId == context.Message.CurrentActionUserId && x.TrialId == subjectVisit.TrialId).Include(x => x.Subject).ToListAsync();


            var trialUserList = await _trialUseRoleRepository.Where(x => x.TrialId == subjectVisit.TrialId && x.TrialUser.IsDeleted == false).Include(x => x.UserRole).Select(x => x.UserRole).ToListAsync();


            var pmandAPm = trialUserList.Where(x => x.UserTypeEnum == UserTypeEnum.APM || x.UserTypeEnum == UserTypeEnum.ProjectManager).ToList();


            var trialInfo = await _trialRepository.FirstOrDefaultAsync(t => t.Id == subjectVisit.TrialId);


            var userinfo = subjectVisit.CurrentActionUser;
            if (userinfo == null)
            {
                return;
            }

            //重新设置当前发送邮件的语言
            var workLanguage = _userRoleRepository.Where(t => t.Id == userinfo.Id).Select(t => t.IdentityUser.UserWorkLanguage).First();
            isEn_US = workLanguage == UserWorkLanguage.US;

            var messageToSend = new MimeMessage();
            //发件地址
            messageToSend.From.Add(new MailboxAddress(_systemEmailConfig.FromName, _systemEmailConfig.FromEmail));
            messageToSend.To.Add(new MailboxAddress(userinfo.FullName, userinfo.EMail));

            foreach (var pm in pmandAPm)
            {
                messageToSend.Cc.Add(new MailboxAddress(pm.FullName, pm.EMail));
            }
            var companyName = isEn_US ? _systemEmailConfig.CompanyShortName : _systemEmailConfig.CompanyShortNameCN;

            var auditStateCode = "AuditStatePE";

            if (trialInfo.QCProcessEnum == TrialQCProcess.DoubleAudit)
            {
                auditStateCode = "AuditStateRC";
            }

            var dictionValue = await CommonEmailHelper.TranslationDictionary(new TranslationDictionaryDto()
            {
                DictionaryRepository = _dictionaryRepository,
                IsEn_US = isEn_US,
                DictionaryList = new List<DictionaryDto>()
         {
          new DictionaryDto (){DictionaryCode= auditStateCode,EnumValue=subjectVisit.AuditState.GetEnumInt(), }, //审核状态

         }
            });

            var subjectcodes = subjectVisitList.Select(x => x.Subject.Code).Distinct().ToList();
            var visitnames = subjectVisitList.Select(x => x.VisitName).Distinct().ToList();

            Func<(string topicStr, string htmlBodyStr), (string topicStr, string htmlBodyStr)> emailConfigFunc = input =>
            {
                var subjectCode = subjectVisit.Subject.Code;
                var topicStr = string.Format(input.topicStr, trialInfo.ResearchProgramNo, subjectCode, subjectVisit.VisitName);
                var htmlBodyStr = string.Format(
                   CommonEmailHelper.ReplaceCompanyName(_systemEmailConfig, input.htmlBodyStr, workLanguage),
                   userinfo.FullName,              // 用户名  {0}
                   trialInfo.ExperimentName,        // 项目   {1}
                   string.Join(',', subjectcodes), // 受试者 {2}
                  string.Join(',', visitnames),             // 访视  {3}
                   dictionValue[0],    // 审核状态 {4}

                   _systemEmailConfig.SiteUrl             // 链接                  {5}
                    );

                return (topicStr, htmlBodyStr);
            };


            await CommonEmailHelper.GetTrialEmailSubejctAndHtmlInfoAndBuildAsync(trialEmailConfig, messageToSend, emailConfigFunc, workLanguage);

            await SendEmailHelper.SendTrialEmailAsync(messageToSend, trialInfo);
        }
    }
}
