using IRaCIS.Core.Application.Helper;
using IRaCIS.Core.Domain;
using MassTransit;
using Microsoft.Extensions.Options;
using MimeKit;
using System.Globalization;

namespace IRaCIS.Core.Application.MassTransit.Consumer;

/// <summary>
/// 用户提交 发送邮件 通知SPM 或者PM   项目默认邮件，不用添加到项目中，直接发送的
/// </summary>
public class UserSiteSurveySubmitedEventConsumer(
      IRepository<Trial> _trialRepository,
      IRepository<TrialSite> _trialSiteRepository,
       IRepository<TrialUserRole> _trialUserRoleRepository,
      IRepository<TrialSiteSurvey> _trialSiteSurveyRepository,
      IRepository<EmailNoticeConfig> _emailNoticeConfigrepository,
      IOptionsMonitor<SystemEmailSendConfig> systemEmailConfig
    ) : IConsumer<UserSiteSurveySubmitedEvent>
{
    private readonly SystemEmailSendConfig _systemEmailConfig = systemEmailConfig.CurrentValue;
    public async Task Consume(ConsumeContext<UserSiteSurveySubmitedEvent> context)
    {
        var isEn_US = CultureInfo.CurrentCulture.Name == StaticData.CultureInfo.en_US;

        var trialSiteSurveyId = context.Message.TrialSiteSurveyId;

        var siteSurveyInfo = _trialSiteSurveyRepository.Where(t => t.Id == trialSiteSurveyId).FirstOrDefault().IfNullThrowException();

        var trialId = siteSurveyInfo.TrialId;

        var scenario = _trialSiteSurveyRepository.Where(t => t.Id != trialSiteSurveyId && t.TrialId == siteSurveyInfo.TrialId && t.TrialSiteId == siteSurveyInfo.TrialSiteId).IgnoreQueryFilters().Any() ?
        EmailBusinessScenario.Approval_UpdateSiteSurvey : EmailBusinessScenario.Approval_SubmitSiteSurvey;


        var emailConfig = _emailNoticeConfigrepository.Where(t => t.BusinessScenarioEnum == scenario && t.IsAutoSend && t.IsEnable).FirstOrDefault();

        if (emailConfig != null)
        {
            var trialInfo = await _trialRepository.FirstOrDefaultAsync(t => t.Id == trialId);
            var siteInfo = await _trialSiteRepository.FirstOrDefaultAsync(t => t.TrialId == trialId && t.Id == siteSurveyInfo.TrialSiteId, true);


            var trialUserList = await _trialUserRoleRepository.Where(t => t.TrialId == siteSurveyInfo.TrialId && t.TrialUser.IsDeleted == false)
                .Where(t => t.UserRole.UserTypeEnum == UserTypeEnum.SPM || t.UserRole.UserTypeEnum == UserTypeEnum.CPM || t.UserRole.UserTypeEnum == UserTypeEnum.ProjectManager || t.UserRole.UserTypeEnum == UserTypeEnum.APM)
                .Select(t => new { t.UserRole.FullName, t.UserRole.IdentityUser.EMail, t.UserRole.UserTypeEnum, t.UserRole.IdentityUser.UserWorkLanguage }).ToListAsync();

            var sPMOrCPMList = trialUserList.Where(t => t.UserTypeEnum == UserTypeEnum.SPM || t.UserTypeEnum == UserTypeEnum.CPM).ToList();
            var pmAndAPMList = trialUserList.Where(t => t.UserTypeEnum == UserTypeEnum.ProjectManager || t.UserTypeEnum == UserTypeEnum.APM).ToList();


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

                var messageToSend = new MimeMessage();

                var toUserName = string.Empty;

                //有SPM 并且参与
                if (trialInfo.IsSPMJoinSiteSurvey && sPMOrCPMList.Count > 0)
                {
                    var lan_SPMOrCPMList = sPMOrCPMList.Where(t => t.UserWorkLanguage == workLanguage);

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

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

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

                }
                else
                {
                    var lan_pmAndAPMList = pmAndAPMList.Where(t => t.UserWorkLanguage == workLanguage);

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

                    toUserName = string.Join('、', lan_pmAndAPMList.Select(t => t.FullName));
                }

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


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

                Func<(string topicStr, string htmlBodyStr), (string topicStr, string htmlBodyStr)> emailConfigFunc = input =>
                {
                    var topicStr = string.Format(input.topicStr, trialInfo.ResearchProgramNo);
                    var htmlBodyStr = string.Format(CommonEmailHelper.ReplaceCompanyName(_systemEmailConfig, input.htmlBodyStr, workLanguage),
                        toUserName,
                    siteInfo.TrialSiteCode,
                    siteInfo.TrialSiteAliasName,

                    siteSurveyInfo.UserName,
                    siteSurveyInfo.Email,
                    siteSurveyInfo.Phone,
                    _systemEmailConfig.SiteUrl
                        );

                    return (topicStr, htmlBodyStr);
                };


                await CommonEmailHelper.GetEmailSubejctAndHtmlInfoAndBuildAsync(emailConfig, messageToSend, emailConfigFunc, workLanguage);

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

    }
}

/// <summary>
/// 调研表初审通过，进行复审发送邮件
/// </summary>
public class SiteSurveySPMSubmitedEventConsumer(
      IRepository<Trial> _trialRepository,
      IRepository<TrialUserRole> _trialUserRoleRepository,
      IRepository<TrialSite> _trialSiteRepository,
      IRepository<TrialSiteSurvey> _trialSiteSurveyRepository,
      IRepository<EmailNoticeConfig> _emailNoticeConfigrepository,
      IOptionsMonitor<SystemEmailSendConfig> systemEmailConfig) : IConsumer<SiteSurveySPMSubmitedEvent>
{
    private readonly SystemEmailSendConfig _systemEmailConfig = systemEmailConfig.CurrentValue;
    public async Task Consume(ConsumeContext<SiteSurveySPMSubmitedEvent> context)
    {

        var isEn_US = CultureInfo.CurrentCulture.Name == StaticData.CultureInfo.en_US;

        var trialSiteSurveyId = context.Message.TrialSiteSurveyId;

        var siteSurveyInfo = _trialSiteSurveyRepository.Where(t => t.Id == trialSiteSurveyId).FirstOrDefault().IfNullThrowException();

        var trialId = siteSurveyInfo.TrialId;

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

        var siteInfo = await _trialSiteRepository.FirstOrDefaultAsync(t => t.TrialId == trialId && t.Id == siteSurveyInfo.TrialSiteId, true);

        var trialUserList = _trialUserRoleRepository.Where(t => t.TrialId == trialId && t.TrialUser.IsDeleted == false)
    .Where(t => t.UserRole.UserTypeEnum == UserTypeEnum.SPM || t.UserRole.UserTypeEnum == UserTypeEnum.CPM || t.UserRole.UserTypeEnum == UserTypeEnum.ProjectManager || t.UserRole.UserTypeEnum == UserTypeEnum.APM)
    .Select(t => new { t.UserRole.IdentityUser.EMail, t.UserRole.FullName, t.UserRole.UserTypeEnum, t.UserRole.IdentityUser.UserWorkLanguage }).ToList();

        var scenario = EmailBusinessScenario.Approval_SubmitSiteSurvey;

        var emailConfig = _emailNoticeConfigrepository.Where(t => t.BusinessScenarioEnum == scenario && t.IsAutoSend && t.IsEnable).FirstOrDefault();

        if (emailConfig != null)
        {

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


                var sPMOrCPMList = trialUserList.Where(t => t.UserTypeEnum == UserTypeEnum.SPM || t.UserTypeEnum == UserTypeEnum.CPM).ToList();
                var pmAndAPMList = trialUserList.Where(t => t.UserTypeEnum == UserTypeEnum.ProjectManager || t.UserTypeEnum == UserTypeEnum.APM).ToList();

                var messageToSend = new MimeMessage();

                var toUserName = string.Empty;

                var lan_pmAndAPMList = pmAndAPMList.Where(t => t.UserWorkLanguage == workLanguage);

                foreach (var item in lan_pmAndAPMList)
                {
                    messageToSend.To.Add(new MailboxAddress(item.FullName, item.EMail));

                    toUserName = string.Join('、', lan_pmAndAPMList.Select(t => t.FullName));
                }

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

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


                Func<(string topicStr, string htmlBodyStr), (string topicStr, string htmlBodyStr)> emailConfigFunc = input =>
                {
                    var topicStr = string.Format(input.topicStr, trialInfo.ResearchProgramNo);
                    var htmlBodyStr = string.Format(CommonEmailHelper.ReplaceCompanyName(_systemEmailConfig, input.htmlBodyStr, workLanguage),
                    toUserName,
                    siteInfo.TrialSiteCode,  //中心编号
                    siteInfo.TrialSiteAliasName,//中心名称

                   siteSurveyInfo.UserName, //联系人
                   siteSurveyInfo.Email,  //联系邮箱
                   siteSurveyInfo.Phone,  //联系电话
                   _systemEmailConfig.SiteUrl
                        );

                    return (topicStr, htmlBodyStr);
                };

                await CommonEmailHelper.GetEmailSubejctAndHtmlInfoAndBuildAsync(emailConfig, messageToSend, emailConfigFunc, workLanguage);

                await SendEmailHelper.SendTrialEmailAsync(messageToSend, trialInfo);

            }


        }



    }
}


/// <summary>
/// 调研表驳回发送邮件    之前已有，需要迁移过来
/// </summary>
public class SiteSurverRejectedEventConsumer(
       IRepository<TrialUserRole> _trialUserRoleRepository,
      IRepository<Trial> _trialRepository,
      IRepository<TrialSite> _trialSiteRepository,
      IRepository<TrialSiteSurvey> _trialSiteSurveyRepository,
     IRepository<EmailNoticeConfig> _emailNoticeConfigrepository,
      IOptionsMonitor<SystemEmailSendConfig> systemEmailConfig
    ) : IConsumer<SiteSurverRejectedEvent>
{
    private readonly SystemEmailSendConfig _systemEmailConfig = systemEmailConfig.CurrentValue;

    public async Task Consume(ConsumeContext<SiteSurverRejectedEvent> context)
    {
        var isEn_US = CultureInfo.CurrentCulture.Name == StaticData.CultureInfo.en_US;

        var trialSiteSurveyId = context.Message.TrialSiteSurveyId;

        var siteSurveyInfo = _trialSiteSurveyRepository.Where(t => t.Id == trialSiteSurveyId, ignoreQueryFilters: true).FirstOrDefault().IfNullThrowException();

        var trialId = siteSurveyInfo.TrialId;

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

        var siteInfo = await _trialSiteRepository.FirstOrDefaultAsync(t => t.TrialId == trialId && t.Id == siteSurveyInfo.TrialSiteId, true);

        var scenario = EmailBusinessScenario.SiteSurveyReject;

        var emailConfig = _emailNoticeConfigrepository.Where(t => t.BusinessScenarioEnum == scenario && t.IsAutoSend && t.IsEnable).FirstOrDefault();

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


                var messageToSend = new MimeMessage();

                var toUserName = siteSurveyInfo.UserName;

                if (context.Message.IsHaveSPMOrCPM)
                {
                    ////PM 驳回到SPM
                    //if (siteSurveyInfo.State == TrialSiteSurveyEnum.CRCSubmitted)
                    //{

                    //    var sPMOrCPMList = _trialUserRoleRepository.Where(t => t.TrialId == trialId && t.TrialUser.IsDeleted == false)
                    //      .Where(t => t.UserRole.UserTypeEnum == UserTypeEnum.SPM || t.UserRole.UserTypeEnum == UserTypeEnum.CPM)
                    //      .Select(t => new { t.UserRole.IdentityUser.EMail, t.UserRole.FullName, t.UserRole.UserTypeEnum, t.UserRole.IdentityUser.UserWorkLanguage }).ToList();

                    //    var lan_SPMOrCPMList = sPMOrCPMList.Where(t => t.UserWorkLanguage == workLanguage);

                    //    foreach (var user in lan_SPMOrCPMList)
                    //    {
                    //        messageToSend.To.Add(new MailboxAddress(user.FullName, user.EMail));
                    //    }

                    //    toUserName = string.Join('、', lan_SPMOrCPMList.Select(t => t.FullName));

                    //}
                    ////SPM 驳回到CRC
                    //else if (siteSurveyInfo.State == TrialSiteSurveyEnum.ToSubmit)
                    //{
                    //    //使用中心国家语言 一致才发送
                    //    if ((siteInfo.Country == StaticData.SiteCountry.US && isEn_US) || (siteInfo.Country == StaticData.SiteCountry.CN && isEn_US == false))
                    //    {
                    //        messageToSend.To.Add(new MailboxAddress(toUserName, siteSurveyInfo.Email));

                    //    }

                    //}

                    // PM 驳回到CRC
                    if (siteSurveyInfo.State == TrialSiteSurveyEnum.ToSubmit)
                    {
                        //使用中心国家语言 一致才发送
                        if ((siteInfo.Country == StaticData.SiteCountry.US && isEn_US) || (siteInfo.Country == StaticData.SiteCountry.CN && isEn_US == false))
                        {
                            messageToSend.To.Add(new MailboxAddress(toUserName, siteSurveyInfo.Email));

                        }

                        var sPMOrCPMList = _trialUserRoleRepository.Where(t => t.TrialId == trialId && t.TrialUser.IsDeleted == false)
                          .Where(t => t.UserRole.UserTypeEnum == UserTypeEnum.SPM || t.UserRole.UserTypeEnum == UserTypeEnum.CPM)
                          .Select(t => new { t.UserRole.IdentityUser.EMail, t.UserRole.FullName, t.UserRole.UserTypeEnum, t.UserRole.IdentityUser.UserWorkLanguage }).ToList();

                        var lan_SPMOrCPMList = sPMOrCPMList.Where(t => t.UserWorkLanguage == workLanguage);

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

                    }
                }
                else
                {
                    //没有SPM  PM驳回到CRC

                    //使用中心国家语言 一致才发送
                    if ((siteInfo.Country == StaticData.SiteCountry.US && isEn_US) || (siteInfo.Country == StaticData.SiteCountry.CN && isEn_US == false))
                    {
                        messageToSend.To.Add(new MailboxAddress(toUserName, siteSurveyInfo.Email));

                    }
                }

                Uri uri = new Uri(_systemEmailConfig.SiteUrl);

                // 获取 Scheme + Host（不包含路径）
                string baseUrl = uri.GetLeftPart(UriPartial.Authority);

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

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


                Func<(string topicStr, string htmlBodyStr), (string topicStr, string htmlBodyStr)> emailConfigFunc = input =>
                {
                    var topicStr = string.Format(input.topicStr, companyName, trialInfo.ResearchProgramNo);
                    var htmlBodyStr = string.Format(CommonEmailHelper.ReplaceCompanyName(_systemEmailConfig, input.htmlBodyStr, workLanguage),
                   toUserName,
                    trialInfo.TrialCode,
                    trialInfo.ResearchProgramNo,
                    trialInfo.ExperimentName,

                    siteInfo.TrialSiteCode,  //中心编号
                    siteInfo.TrialSiteAliasName,//中心名称
                    siteSurveyInfo.LatestBackReason,  //驳回原因
                    $"{baseUrl}/researchLogin?trialId={trialId}",  //链接
                       (siteSurveyInfo.State == TrialSiteSurveyEnum.ToSubmit ? "inline - block" : "none"),
                       trialInfo.LinkVerificationCode.IsNullOrEmpty()? trialInfo.ResearchProgramNo: trialInfo.LinkVerificationCode
                        );

                    return (topicStr, htmlBodyStr);
                };

                await CommonEmailHelper.GetEmailSubejctAndHtmlInfoAndBuildAsync(emailConfig, messageToSend, emailConfigFunc);

                await SendEmailHelper.SendTrialEmailAsync(messageToSend, trialInfo);

            }


        }




    }
}
