using Amazon.Runtime.Internal.Util;
using DocumentFormat.OpenXml;
using IRaCIS.Core.Application.Helper;
using IRaCIS.Core.Domain.Share;
using IRaCIS.Core.Infrastructure;
using MimeKit;
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;

public static class OldRecurringEmailHelper
{
    public static string EmailNamePlaceholder => StaticData.EmailSend.EmailNamePlaceholder;


    //发送项目邮件的通用方法 已经处理
    public static async Task SendTrialEmailAsync(
      IRepository<TrialEmailNoticeConfig> _trialEmailNoticeConfigRepository,
      IRepository<Trial> _trialRepository,
      IRepository<TrialUserRole> _trialUserRoleRepository,
      IRepository<VisitTask> _visitTaskRepository,
      IRepository<TrialSiteUserRole> _trialSiteUserRoleRepository,

        Guid trialId, EmailBusinessScenario businessScenario, 
        Func<TrialEmailNoticeConfig, (string topicStr, string htmlBodyStr, bool isEn_us, Guid? onlyToUserId)> topicAndHtmlFunc,
        Guid? trialSiteId = null)
    {
        //找到配置
        var trialEmailConfig = await _trialEmailNoticeConfigRepository.Where(t => t.TrialId == trialId  && t.BusinessScenarioEnum == businessScenario, ignoreQueryFilters: true)
       .Include(t => t.TrialEmailNoticeUserList).Include(t => t.TrialEmailBlackUserList).FirstOrDefaultAsync();

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

        if (trialEmailConfig == null || trialEmailConfig.IsAutoSend == false || trialEmailConfig.IsEnable == false)
        {
           
        }
        else
        {
            var sendEmailConfig = new SMTPEmailConfig();

            var (topicStr, htmlBodyStr, isEn_us, onlyToUserId) = topicAndHtmlFunc(trialEmailConfig);


            sendEmailConfig.TopicDescription = topicStr;
            sendEmailConfig.HtmlBodyStr = htmlBodyStr;


            var blackUserIdList = trialEmailConfig.TrialEmailBlackUserList.Select(t => t.UserId).ToList();


            var toUserTypeEnumList = trialEmailConfig.TrialEmailNoticeUserList.Where(t => t.EmailUserType == EmailUserType.To).Select(c => c.UserType).ToList();

            var copyUserTypeEnumList = trialEmailConfig.TrialEmailNoticeUserList.Where(t => t.EmailUserType == EmailUserType.Copy).Select(c => c.UserType).ToList();

            var allUserTypeEnumList = toUserTypeEnumList.Union(copyUserTypeEnumList).Distinct().ToList();

            var allUserList = await _trialUserRoleRepository.Where(t => t.TrialId == trialId && allUserTypeEnumList.Contains(t.UserRole.UserTypeEnum)).Select(t => new { t.UserId, t.UserRole.IdentityUser.EMail, t.UserRole.FullName, t.UserRole.UserTypeEnum }).ToListAsync();


            var toUserList = allUserList.Where(t => toUserTypeEnumList.Contains(t.UserTypeEnum))
               .ToList();

            //收件人 有CRC  CRA  ， CRC  CRA的账户要按照中心发送
            if (trialSiteId == null && toUserTypeEnumList.Any(t => t == UserTypeEnum.ClinicalResearchCoordinator || t == UserTypeEnum.CRA) && onlyToUserId == null)
            {
                throw new BusinessValidationFailedException("当前场景收件人包含CRC CRA,但是没有siteId,请联系后端开发");
            }
            if (trialSiteId != null && toUserTypeEnumList.Any(t => t == UserTypeEnum.ClinicalResearchCoordinator || t == UserTypeEnum.CRA))
            {
                var curentSiteUserIdList = _trialSiteUserRoleRepository.Where(t => t.TrialId == trialId && t.TrialSiteId == trialSiteId).Select(t => t.UserId).ToList();

                toUserList = toUserList.Where(t => (t.UserTypeEnum != UserTypeEnum.CRA && t.UserTypeEnum != UserTypeEnum.ClinicalResearchCoordinator) || curentSiteUserIdList.Contains(t.UserId)).ToList();
            }


            //去除黑名单
            toUserList = toUserList.Where(t => !blackUserIdList.Contains(t.UserId)).ToList();

            var copyUserList = allUserList.Where(t => copyUserTypeEnumList.Contains(t.UserTypeEnum))
                .Where(t => !blackUserIdList.Contains(t.UserId)).ToList();

            if (trialSiteId != null && copyUserTypeEnumList.Any(t => t == UserTypeEnum.ClinicalResearchCoordinator || t == UserTypeEnum.CRA))
            {
                var curentSiteUserIdList = _trialSiteUserRoleRepository.Where(t => t.TrialId == trialId && t.TrialSiteId == trialSiteId).Select(t => t.UserId).ToList();

                copyUserList = copyUserList.Where(t => (t.UserTypeEnum != UserTypeEnum.CRA && t.UserTypeEnum != UserTypeEnum.ClinicalResearchCoordinator) || curentSiteUserIdList.Contains(t.UserId)).ToList();
            }

            if (onlyToUserId != null)
            {
                toUserList = toUserList.Where(t => t.UserId == onlyToUserId).ToList();
            }
            else
            {
                sendEmailConfig.HtmlBodyStr = htmlBodyStr.Replace(EmailNamePlaceholder, string.Join(isEn_us ? ", " : "、", toUserList.Select(t => t.FullName).ToList()));
            }

            if (toUserList.Count == 0)
            {
                //---没有收件人，无法发送邮件
                throw new BusinessValidationFailedException(I18n.T("TrialEmailN_NoRecipient"));
            }


            if (trialEmailConfig.FromEmail.Contains("@") && !string.IsNullOrEmpty(trialEmailConfig.FromEmail))
            {

                sendEmailConfig.FromEmailAddress = new MimeKit.MailboxAddress(trialEmailConfig.FromName, trialEmailConfig.FromEmail);
                sendEmailConfig.AuthorizationCode = trialEmailConfig.AuthorizationCode;
                sendEmailConfig.UserName = trialEmailConfig.FromEmail;

                sendEmailConfig.Host = trialEmailConfig.SMTPServerAddress;
                sendEmailConfig.Port = trialEmailConfig.SMTPServerPort;
            }
            else
            {
                //---项目发件邮箱配置有误，请核实
                throw new BusinessValidationFailedException(I18n.T("TrialEmailN_InvalidEmailConfig"));
            }

            foreach (var item in toUserList)
            {

                if (item.EMail.Contains("@") && !string.IsNullOrEmpty(item.EMail))
                {

                    sendEmailConfig.ToMailAddressList.Add(new MimeKit.MailboxAddress(item.FullName, item.EMail));

                }
            }
            foreach (var item in copyUserList)
            {

                if (item.EMail.Contains("@") && !string.IsNullOrEmpty(item.EMail))
                {

                    sendEmailConfig.CopyToMailAddressList.Add(new MimeKit.MailboxAddress(item.FullName, item.EMail));

                }
            }

            //邮件附件  这里是原格式发送，不是PDF

            //if (trialEmailConfig.AttachCNPath != string.Empty && trialEmailConfig.AttachPath != string.Empty)
            //{
            //    var phyPath = FileStoreHelper.GetPhysicalFilePath(_hostEnvironment, isEn_us? trialEmailConfig.AttachName: trialEmailConfig.AttachNameCN);

            //    //先预先生成了邮件，发送预先生成的邮件
            //    sendEmailConfig.EmailAttachMentConfigList.Add(new EmailAttachMentConfig()
            //    {
            //        FileName = $"{attachPrefix}_{Path.GetFileName(_userInfo.IsEn_Us ? trialEmailConfig.AttachName : trialEmailConfig.AttachNameCN)}",

            //        FileStream = File.OpenRead(phyPath),
            //    });
            //}

            if (sendEmailConfig != null)
            {

                await SendEmailHelper.SendEmailAsync(sendEmailConfig, trialInfo);
            }


        }
    }


}

