using IRaCIS.Core.Application.Helper;
using IRaCIS.Core.Application.MassTransit.Command;
using IRaCIS.Core.Application.MassTransit.Consumer.Dto;
using IRaCIS.Core.Domain;
using IRaCIS.Core.Domain.BaseModel;
using IRaCIS.Core.Domain.Models;
using IRaCIS.Core.Domain.Share;
using IRaCIS.Core.Infra.EFCore.Common;
using MassTransit;
using Microsoft.Extensions.Options;
using MimeKit;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Reactive.Subjects;
using System.Text;
using System.Threading.Tasks;

namespace IRaCIS.Core.Application.MassTransit.Consumer;

/// <summary>
/// 加急的医学反馈任务  通知MIM
/// </summary>
public class UrgentMedicalReviewAddedEventConsumer(
      IRepository<UserRole> _userRoleRepository,
       IRepository<TaskMedicalReview> _taskMedicalReviewRepository,
      IRepository<Trial> _trialRepository,
        IRepository<SubjectVisit> _subjectVisitRepository,
      IRepository<ReadingQuestionCriterionTrial> _readingQuestionCriterionTrialRepository,
      IRepository<VisitTask> _visitTaskRepository,
         IRepository<Dictionary> _dictionaryRepository,
      IRepository<TrialEmailNoticeConfig> _trialEmailNoticeConfigrepository,
      IOptionsMonitor<SystemEmailSendConfig> systemEmailConfig
    ) : IConsumer<UrgentMedicalReviewAddedEvent>
{
    private readonly SystemEmailSendConfig _systemEmailConfig = systemEmailConfig.CurrentValue;

    /// <summary>
    ///  加急的医学反馈任务  通知MIM    (026,027)
    /// </summary>
    /// <param name="context"></param>
    /// <returns></returns>
    /// <exception cref="NotImplementedException"></exception>
    public async Task Consume(ConsumeContext<UrgentMedicalReviewAddedEvent> context)
    {
        Console.WriteLine("发送(026,027) 【加急的医学反馈任务  通知MIM】邮件！！！");
        var isEn_US = CultureInfo.CurrentCulture.Name == StaticData.CultureInfo.en_US;

        var medicalReviewId = context.Message.MedicalReviewId;

        var medicalReview = await _taskMedicalReviewRepository.Where(x => x.Id == medicalReviewId).Include(x => x.VisitTask).Include(x => x.MedicalManagerUser).FirstOrDefaultAsync();


        if (medicalReview.MedicalManagerUserId == null)
        {
            Console.WriteLine("MIMId为空 ID" + medicalReviewId);
            return;
        }

        var trialId = medicalReview.TrialId;

        var scenario = context.Message.IsPD ? EmailBusinessScenario.PDVerification_MedicalQC : EmailBusinessScenario.EligibilityVerification_MedicalQC;

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

        if (trialEmailConfig != null)
        {


            var criterion = await _readingQuestionCriterionTrialRepository.FirstOrDefaultAsync(x => x.Id == medicalReview.VisitTask.TrialReadingCriterionId);
            var userinfo = await _userRoleRepository.Where(x => x.Id == medicalReview.MedicalManagerUserId).Include(x => x.IdentityUser).FirstOrDefaultAsync();

            var taskInfo = await _visitTaskRepository.Where(x => x.Id == medicalReview.VisitTaskId).Include(x => x.SourceSubjectVisit).Include(x => x.ReadModule).Include(x => x.Subject).FirstNotNullAsync();


            var visitid = taskInfo.SourceSubjectVisit == null ? taskInfo.ReadModule.SubjectVisitId : taskInfo.SourceSubjectVisitId;


            var subjectVisit = await _subjectVisitRepository.Where(x => x.Id == visitid).FirstOrDefaultAsync();

            var workLanguage = userinfo.IdentityUser?.UserWorkLanguage;
            var userIsEn_US = workLanguage.HasValue ? workLanguage.Value == UserWorkLanguage.US : isEn_US;

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

            var trialInfo = await _trialRepository.FirstOrDefaultAsync(t => t.Id == medicalReview.TrialId);
            var companyName = userIsEn_US ? _systemEmailConfig.CompanyShortName : _systemEmailConfig.CompanyShortNameCN;


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

                DictionaryRepository = _dictionaryRepository,
                IsEn_US = userIsEn_US,


                DictionaryList = new List<DictionaryDto>()
            {
             new DictionaryDto (){DictionaryCode= "ReadingCategory",EnumValue=taskInfo.ReadingCategory.GetEnumInt(), },
             new DictionaryDto (){DictionaryCode= "MedicalReviewDoctorUserIdea",EnumValue=medicalReview.DoctorUserIdeaEnum.GetEnumInt(), },
             new DictionaryDto (){DictionaryCode= "MedicalReviewAuditState",EnumValue=medicalReview.AuditState.GetEnumInt(), },
             new DictionaryDto (){DictionaryCode= "YesOrNo",EnumValue=taskInfo.IsUrgent.ToString().ToLower(), }
            }
            });

            Func<(string topicStr, string htmlBodyStr), (string topicStr, string htmlBodyStr)> emailConfigFunc = input =>
            {
                var subjectName = taskInfo.BlindSubjectCode.IsNullOrEmpty() ? taskInfo.Subject.Code : taskInfo.BlindSubjectCode;
                var topicStr = string.Format(input.topicStr, trialInfo.ResearchProgramNo, subjectName, taskInfo.TaskBlindName);
                var htmlBodyStr = string.Format(
                   CommonEmailHelper.ReplaceCompanyName(_systemEmailConfig, input.htmlBodyStr, workLanguage),
                   userinfo.FullName,              // 用户名  {0}
                   trialInfo.ExperimentName,        // 项目   {1}
                   criterion.CriterionName,  // 阅片标准       {2}
                   subjectName, // 受试者 {3}
                   taskInfo.TaskBlindName,             // 访视  {4}
                   dictionValue[0],      // 任务类型            {5}
                                         //dictionValue[1],     // 阅片人是否同意        {6}
                   dictionValue[2],     // 审核状态             {6}
                   dictionValue[3],    // 是否加急               {7}
                  _systemEmailConfig.SiteUrl              // 链接                    {8}
                    );

                return (topicStr, htmlBodyStr);
            };

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

            await SendEmailHelper.SendTrialEmailAsync(messageToSend, trialInfo);

        }

    }
}

//IR 回复医学反馈通知MIM
public class UrgentIRRepliedMedicalReviewConsumer(
      IRepository<UserRole> _userRoleRepository,
       IRepository<TaskMedicalReview> _taskMedicalReviewRepository,
      IRepository<Trial> _trialRepository,
        IRepository<SubjectVisit> _subjectVisitRepository,
      IRepository<ReadingQuestionCriterionTrial> _readingQuestionCriterionTrialRepository,
      IRepository<VisitTask> _visitTaskRepository,
         IRepository<Dictionary> _dictionaryRepository,
      IRepository<TrialEmailNoticeConfig> _trialEmailNoticeConfigrepository,
      IOptionsMonitor<SystemEmailSendConfig> systemEmailConfig) : IConsumer<UrgentIRRepliedMedicalReview>
{
    private readonly SystemEmailSendConfig _systemEmailConfig = systemEmailConfig.CurrentValue;


    //IR 回复医学反馈通知MIM
    public async Task Consume(ConsumeContext<UrgentIRRepliedMedicalReview> context)
    {
        Console.WriteLine("发送(028,029) 【IR 回复医学反馈通知MIM】邮件！！！");
        var isEn_US = CultureInfo.CurrentCulture.Name == StaticData.CultureInfo.en_US;

        var medicalReviewId = context.Message.MedicalReviewId;

        var medicalReview = await _taskMedicalReviewRepository.Where(x => x.Id == medicalReviewId).Include(x => x.VisitTask).Include(x => x.MedicalManagerUser).FirstOrDefaultAsync();

        if (medicalReview.MedicalManagerUserId == null)
        {
            Console.WriteLine("MIMId为空 ID" + medicalReviewId);
            return;
        }
        var trialId = medicalReview.TrialId;

        var scenario = context.Message.IsPD ? EmailBusinessScenario.PDVerification_ExpeditedMedicalQCResponse : EmailBusinessScenario.EligibilityVerification_ExpeditedMedicalQCResponse;

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

        if (trialEmailConfig != null)
        {


          
            var criterion = await _readingQuestionCriterionTrialRepository.FirstOrDefaultAsync(x => x.Id == medicalReview.VisitTask.TrialReadingCriterionId);
            var userinfo = await _userRoleRepository.Where(x => x.Id == medicalReview.MedicalManagerUserId).Include(x => x.IdentityUser).FirstOrDefaultAsync();

            var taskInfo = await _visitTaskRepository.Where(x => x.Id == medicalReview.VisitTaskId).Include(x => x.SourceSubjectVisit).Include(x => x.ReadModule).Include(x => x.Subject).FirstNotNullAsync();


            var visitid = taskInfo.SourceSubjectVisit == null ? taskInfo.ReadModule.SubjectVisitId : taskInfo.SourceSubjectVisitId;


            var subjectVisit = await _subjectVisitRepository.Where(x => x.Id == visitid).FirstOrDefaultAsync();

            var workLanguage = userinfo.IdentityUser?.UserWorkLanguage;
            var userIsEn_US = workLanguage.HasValue ? workLanguage.Value == UserWorkLanguage.US : isEn_US;


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

            var trialInfo = await _trialRepository.FirstOrDefaultAsync(t => t.Id == medicalReview.TrialId);
            var companyName = userIsEn_US ? _systemEmailConfig.CompanyShortName : _systemEmailConfig.CompanyShortNameCN;


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

                DictionaryRepository = _dictionaryRepository,
                IsEn_US = userIsEn_US,


                DictionaryList = new List<DictionaryDto>()
            {
             new DictionaryDto (){DictionaryCode= "ReadingCategory",EnumValue=taskInfo.ReadingCategory.GetEnumInt(), },
             new DictionaryDto (){DictionaryCode= "MedicalReviewDoctorUserIdea",EnumValue=medicalReview.DoctorUserIdeaEnum.GetEnumInt(), },
             new DictionaryDto (){DictionaryCode= "MedicalReviewAuditState",EnumValue=medicalReview.AuditState.GetEnumInt(), },
             new DictionaryDto (){DictionaryCode= "YesOrNo",EnumValue=taskInfo.IsUrgent.ToString().ToLower(), }
            }
            });

            Func<(string topicStr, string htmlBodyStr), (string topicStr, string htmlBodyStr)> emailConfigFunc = input =>
            {
                var subjectCode = taskInfo.BlindSubjectCode.IsNullOrEmpty() ? taskInfo.Subject.Code : taskInfo.BlindSubjectCode;
                var topicStr = string.Format(input.topicStr, trialInfo.ResearchProgramNo, subjectCode, taskInfo.TaskBlindName);
                var htmlBodyStr = string.Format(
                   CommonEmailHelper.ReplaceCompanyName(_systemEmailConfig, input.htmlBodyStr, workLanguage),
                   userinfo.FullName,              // 用户名  {0}
                   trialInfo.ExperimentName,        // 项目   {1}
                   criterion.CriterionName,  // 阅片标准       {2}
                   subjectCode, // 受试者 {3}
                   taskInfo.TaskBlindName,             // 访视  {4}
                   dictionValue[0],      // 任务类型            {5}
                   dictionValue[1],     // 阅片人是否同意        {6}
                   dictionValue[2],     // 审核状态             {7}
                   dictionValue[3],    // 是否加急               {8}
                  _systemEmailConfig.SiteUrl              // 链接                    {9}
                    );

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

            await SendEmailHelper.SendTrialEmailAsync(messageToSend, trialInfo);
        }

    }
}

/// <summary>
/// MIM 回复医学返回通知IR
/// </summary>
public class UrgentMIMRepliedMedicalReviewConsumer(
      IRepository<UserRole> _userRoleRepository,
       IRepository<TaskMedicalReview> _taskMedicalReviewRepository,
      IRepository<Trial> _trialRepository,
        IRepository<SubjectVisit> _subjectVisitRepository,
      IRepository<ReadingQuestionCriterionTrial> _readingQuestionCriterionTrialRepository,
      IRepository<VisitTask> _visitTaskRepository,
         IRepository<Dictionary> _dictionaryRepository,
      IRepository<TrialEmailNoticeConfig> _trialEmailNoticeConfigrepository,
      IOptionsMonitor<SystemEmailSendConfig> systemEmailConfig) : IConsumer<UrgentMIMRepliedMedicalReview>
{

    private readonly SystemEmailSendConfig _systemEmailConfig = systemEmailConfig.CurrentValue;

    /// <summary>
    /// MIM 回复医学返回通知IR
    /// </summary>
    /// <param name="context"></param>
    /// <returns></returns>
    public async Task Consume(ConsumeContext<UrgentMIMRepliedMedicalReview> context)
    {
        Console.WriteLine("发送(022) 【加急医学反馈】邮件！！！");
        var isEn_US = CultureInfo.CurrentCulture.Name == StaticData.CultureInfo.en_US;


        var medicalReviewId = context.Message.MedicalReviewId;

        var medicalReview = await _taskMedicalReviewRepository.Where(x => x.Id == medicalReviewId).Include(x => x.VisitTask).Include(x => x.MedicalManagerUser).FirstOrDefaultAsync();

        if (medicalReview.MedicalManagerUserId == null)
        {
            Console.WriteLine("MIMId为空 ID" + medicalReviewId);
            return;
        }

        var trialId = medicalReview.TrialId;

        var scenario = EmailBusinessScenario.ExpeditedMedicalQCToIR;

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

        if (trialEmailConfig != null)
        {


            var criterion = await _readingQuestionCriterionTrialRepository.FirstOrDefaultAsync(x => x.Id == medicalReview.VisitTask.TrialReadingCriterionId);
            var taskInfo = await _visitTaskRepository.Where(x => x.Id == medicalReview.VisitTaskId).Include(x => x.SourceSubjectVisit).Include(x => x.ReadModule).Include(x => x.Subject).FirstNotNullAsync();

            var userinfo = await _userRoleRepository.Where(x => x.Id == taskInfo.DoctorUserId).Include(x => x.IdentityUser).FirstOrDefaultAsync();




            var visitid = taskInfo.SourceSubjectVisit == null ? taskInfo.ReadModule.SubjectVisitId : taskInfo.SourceSubjectVisitId;


            var subjectVisit = await _subjectVisitRepository.Where(x => x.Id == visitid).FirstOrDefaultAsync();

            var workLanguage = userinfo.IdentityUser?.UserWorkLanguage;
            var userIsEn_US = workLanguage.HasValue ? workLanguage.Value == UserWorkLanguage.US : isEn_US;



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

            var trialInfo = await _trialRepository.FirstOrDefaultAsync(t => t.Id == medicalReview.TrialId);
            var companyName = userIsEn_US ? _systemEmailConfig.CompanyShortName : _systemEmailConfig.CompanyShortNameCN;


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

                DictionaryRepository = _dictionaryRepository,
                IsEn_US = userIsEn_US,


                DictionaryList = new List<DictionaryDto>()
            {
             new DictionaryDto (){DictionaryCode= "ReadingCategory",EnumValue=taskInfo.ReadingCategory.GetEnumInt(), },
             new DictionaryDto (){DictionaryCode= "IsPass",EnumValue=medicalReview.IsHaveQuestion.ToString().ToLower(), },// 审核结论
             new DictionaryDto (){DictionaryCode= "AuditAdvice",EnumValue=medicalReview.AuditAdviceEnum.GetEnumInt(), },// 审核建议
             new DictionaryDto (){DictionaryCode= "YesOrNo",EnumValue=taskInfo.IsUrgent.ToString().ToLower(), }, //是否加急         
            }
            });

            Func<(string topicStr, string htmlBodyStr), (string topicStr, string htmlBodyStr)> emailConfigFunc = input =>
            {
                var subjectCode = taskInfo.BlindSubjectCode.IsNullOrEmpty() ? taskInfo.Subject.Code : taskInfo.BlindSubjectCode;
                var topicStr = string.Format(input.topicStr, trialInfo.ResearchProgramNo, subjectCode, taskInfo.TaskBlindName);
                var htmlBodyStr = string.Format(
                   CommonEmailHelper.ReplaceCompanyName(_systemEmailConfig, input.htmlBodyStr, workLanguage),
                   userinfo.FullName,              // 用户名  {0}
                   trialInfo.ExperimentName,        // 项目   {1}
                   subjectCode, // 受试者 {2}
                   taskInfo.TaskBlindName,             // 访视  {3}
                   criterion.CriterionName,  // 阅片标准       {4}
                   dictionValue[0],      // 任务类型            {5}
                   dictionValue[1],      // 审核结论           {6}
                   dictionValue[2],     // 医学审核建议        {7}
                   dictionValue[3],    // 是否加急               {8}

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

                return (topicStr, htmlBodyStr);
            };

             await CommonEmailHelper.GetTrialEmailSubejctAndHtmlInfoAndBuildAsync(trialEmailConfig, messageToSend, emailConfigFunc, workLanguage);
            await SendEmailHelper.SendTrialEmailAsync(messageToSend, trialInfo);
        }
    }
}

/// <summary>
/// 加急阅片 IR 申请重阅  或者PM 申请重阅
/// </summary>
public class UrgentIRApplyedReReadingConsumer(
      IRepository<UserRole> _userRoleRepository,
        IRepository<TrialUserRole> _trialUseRoleRepository,
       IRepository<TaskMedicalReview> _taskMedicalReviewRepository,
      IRepository<Trial> _trialRepository,
        IRepository<SubjectVisit> _subjectVisitRepository,
      IRepository<ReadingQuestionCriterionTrial> _readingQuestionCriterionTrialRepository,
      IRepository<VisitTask> _visitTaskRepository,
         IRepository<Dictionary> _dictionaryRepository,
      IRepository<TrialEmailNoticeConfig> _trialEmailNoticeConfigrepository,
      IOptionsMonitor<SystemEmailSendConfig> systemEmailConfig) : IConsumer<UrgentApplyedReReading>
{

    private readonly SystemEmailSendConfig _systemEmailConfig = systemEmailConfig.CurrentValue;
    public async Task Consume(ConsumeContext<UrgentApplyedReReading> context)
    {
        Console.WriteLine("发送(024,025) 【加急医学反馈】邮件！！！");
        var isEn_US = CultureInfo.CurrentCulture.Name == StaticData.CultureInfo.en_US;

        var visitTaskId = context.Message.VisitTaskId;

        var taskInfo = await _visitTaskRepository.Where(x => x.Id == visitTaskId).Include(x => x.SourceSubjectVisit).Include(x => x.ReadModule).Include(x => x.Subject).FirstNotNullAsync();

        var trialId=taskInfo.TrialId;

        var scenario = context.Message.ReReadingApplyState == ReReadingApplyState.TrialGroupHaveApplyed ? EmailBusinessScenario.ReReadFromPMApproval : EmailBusinessScenario.ReReadFromIRApproval;

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

        if (trialEmailConfig != null)
        {

          
            var criterion = await _readingQuestionCriterionTrialRepository.FirstOrDefaultAsync(x => x.Id == taskInfo.TrialReadingCriterionId);


            var doctorInfo = await _userRoleRepository.Where(x => x.Id == taskInfo.DoctorUserId).FirstOrDefaultAsync();

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

            var userinfoList = trialUserList.Where(x => x.UserTypeEnum == UserTypeEnum.ProjectManager || x.UserTypeEnum == UserTypeEnum.APM).ToList();
            if (context.Message.ReReadingApplyState == ReReadingApplyState.TrialGroupHaveApplyed)
            {
                userinfoList = trialUserList.Where(x => x.UserTypeEnum == UserTypeEnum.CPM || x.UserTypeEnum == UserTypeEnum.SPM).ToList();
            }

            var visitid = taskInfo.SourceSubjectVisit == null ? taskInfo.ReadModule.SubjectVisitId : taskInfo.SourceSubjectVisitId;


            var subjectVisit = await _subjectVisitRepository.Where(x => x.Id == visitid).FirstOrDefaultAsync();

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

            var userWorkLanguageList = userinfoList.Select(x => x.UserWorkLanguage).Distinct().ToList();

            foreach (var workLanguage in userWorkLanguageList)
            {
                var langUserinfoList = userinfoList.Where(x => x.UserWorkLanguage == workLanguage).ToList();
                if (!langUserinfoList.Any()) continue;

                var userIsEn_US =  workLanguage == UserWorkLanguage.US;

                var dictionValue = await CommonEmailHelper.TranslationDictionary(new TranslationDictionaryDto()
                {
                    DictionaryRepository = _dictionaryRepository,
                    IsEn_US = userIsEn_US,
                    DictionaryList = new List<DictionaryDto>()
                    {
                        new DictionaryDto (){DictionaryCode= "ReadingCategory",EnumValue=taskInfo.ReadingCategory.GetEnumInt(), }, //任务类型
                        new DictionaryDto (){DictionaryCode= "RequestReReadingResult",EnumValue="0", }, //审批结果 都是待审批
                    }
                });

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

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

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

                Func<(string topicStr, string htmlBodyStr), (string topicStr, string htmlBodyStr)> emailConfigFunc = input =>
                {
                    var subjectCode = taskInfo.BlindSubjectCode.IsNullOrEmpty() ? taskInfo.Subject.Code : taskInfo.BlindSubjectCode;
                    var topicStr = string.Format(input.topicStr, trialInfo.ResearchProgramNo, subjectCode, taskInfo.TaskBlindName);
                    var htmlBodyStr = string.Format(
                       CommonEmailHelper.ReplaceCompanyName(_systemEmailConfig, input.htmlBodyStr, workLanguage),
                       string.Join(',', userNames),              // 用户名  {0}
                       trialInfo.ExperimentName,        // 项目   {1}
                       subjectCode, // 受试者 {2}
                       taskInfo.TaskBlindName,             // 访视  {3}
                       dictionValue[0],    // 任务类型 {4}
                       doctorInfo.FullName,                       // 阅片人 {5}
                       criterion.CriterionName,                      // 阅片标准 {6}
                       dictionValue[1],                                               // 审批结果 {7}
                       _systemEmailConfig.SiteUrl             // 链接                  {8}
                        );

                    return (topicStr, htmlBodyStr);
                };

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

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


    }
}

