using IRaCIS.Core.Application.Helper;
using IRaCIS.Core.Application.MassTransit.Consumer;
using IRaCIS.Core.Domain.Share;
using IRaCIS.Core.Infrastructure;
using Microsoft.Extensions.Options;

namespace IRaCIS.Core.Application.Service
{

    public interface IEmailSendService
    {
        Task SendEnrollOrPdEmail(Guid visitTaskId, bool? isEnrollment, bool? isPDConfirm);

        Task<(TrialEmailNoticeConfig?, SMTPEmailConfig?)> BuildEmailConfig(Guid trialId, CriterionType criterionType, EmailBusinessScenario businessScenario, Func<TrialEmailNoticeConfig, (string topicStr, string htmlBodyStr, bool isEn_us, Guid? onlyToUserId)> topicAndHtmlFunc, Guid? siteId = null);
    }

    public class EmailSendService(IRepository<TrialEmailNoticeConfig> _trialEmailNoticeConfigRepository,
      IRepository<Trial> _trialRepository,
      IRepository<TrialUserRole> _trialUserRoleRepository,
      IRepository<VisitTask> _visitTaskRepository,
      IRepository<TrialSiteUserRole> _trialSiteUserRoleRepository,
      IOptionsMonitor<SystemEmailSendConfig> _SystemEmailSendConfig, IMapper _mapper, IUserInfo _userInfo, IStringLocalizer _localizer) : BaseService, IEmailSendService
    {
        private readonly SystemEmailSendConfig _systemEmailConfig = _SystemEmailSendConfig.CurrentValue;

        public static string EmailNamePlaceholder => StaticData.EmailSend.EmailNamePlaceholder;



        //入组确认/PD确认


        public async Task SendEnrollOrPdEmail(Guid visitTaskId, bool? isEnrollment, bool? isPDConfirm)
        {
            EmailBusinessScenario businessScenarioEnum;

            bool? result = null;

            if (isEnrollment != null && isPDConfirm == null)
            {
                businessScenarioEnum = EmailBusinessScenario.EnrollConfirmed;

                result = isEnrollment;
            }
            else
            {
                businessScenarioEnum = EmailBusinessScenario.PDConfirmed;

                result = isPDConfirm;
            }

            var taskInfo = await _visitTaskRepository.Where(t => t.Id == visitTaskId).Select(t => new
            {
                t.Subject.TrialSiteId,
                t.Trial.ResearchProgramNo,
                t.Subject.TrialSite.TrialSiteCode,
                SubjectCode = t.Subject.Code,
                t.Trial.Sponsor.SponsorName,
                t.SourceSubjectVisit.VisitName,
                t.TrialId,
                t.TrialReadingCriterion.CriterionType,

            }).FirstNotNullAsync();

            //找到当前收件人语言
            var workLanguageList = _trialUserRoleRepository.Where(t => t.TrialId == taskInfo.TrialId && t.UserRole.UserTypeEnum == UserTypeEnum.ClinicalResearchCoordinator).Select(t => t.UserRole.IdentityUser.UserWorkLanguage).Distinct().ToList();

            foreach (var workLanguage in workLanguageList)
            {
                //设置工作语言
                var isEn_us = workLanguage == UserWorkLanguage.US;

                var resultStr = isEn_us ? (result == true ? "Yes" : "No") : (result == true ? "是" : "否");



                if (isEnrollment == true)
                {
                    Func<TrialEmailNoticeConfig, (string topicStr, string htmlBodyStr, bool isEn_us, Guid? onlyToUserId)> topicAndHtmlFunc = trialEmailConfig =>
                    {
                        var topicStr = string.Format(isEn_us ? trialEmailConfig.EmailTopic : trialEmailConfig.EmailTopicCN, taskInfo.ResearchProgramNo, taskInfo.SubjectCode);

                        var htmlBodyStr = string.Format(isEn_us ? trialEmailConfig.EmailHtmlContent : trialEmailConfig.EmailHtmlContentCN,
                           EmailNamePlaceholder, taskInfo.ResearchProgramNo, taskInfo.SubjectCode, resultStr);


                        return (topicStr, htmlBodyStr, isEn_us, null);
                    };

                    await SendTrialEmailAsync(taskInfo.TrialId, taskInfo.CriterionType, businessScenarioEnum, topicAndHtmlFunc, taskInfo.TrialSiteId);
                }
                else
                {
                    Func<TrialEmailNoticeConfig, (string topicStr, string htmlBodyStr, bool isEn_us, Guid? onlyToUserId)> topicAndHtmlFunc = trialEmailConfig =>
                    {
                        var topicStr = string.Format(isEn_us ? trialEmailConfig.EmailTopic : trialEmailConfig.EmailTopicCN, taskInfo.ResearchProgramNo, taskInfo.SubjectCode, taskInfo.VisitName);

                        var htmlBodyStr = string.Format(isEn_us ? trialEmailConfig.EmailHtmlContent : trialEmailConfig.EmailHtmlContentCN,
                           EmailNamePlaceholder, taskInfo.ResearchProgramNo, taskInfo.SubjectCode, taskInfo.VisitName, resultStr);


                        return (topicStr, htmlBodyStr, isEn_us, null);
                    };

                    await SendTrialEmailAsync(taskInfo.TrialId, taskInfo.CriterionType, businessScenarioEnum, topicAndHtmlFunc, taskInfo.TrialSiteId);
                }

            }

        }





        public async Task SendTrialEmailAsync(Guid trialId, CriterionType criterionType, EmailBusinessScenario businessScenario, Func<TrialEmailNoticeConfig, (string topicStr, string htmlBodyStr, bool isEn_us, Guid? onlyToUserId)> topicAndHtmlFunc, Guid? trialSiteId = null, Func<TrialEmailNoticeConfig, SMTPEmailConfig, SMTPEmailConfig> emailAttachFunc = null)
        {
            var (trialEmailConfig, sendEmailConfig) = await BuildEmailConfig(trialId, criterionType, businessScenario, topicAndHtmlFunc, trialSiteId);

            if (sendEmailConfig != null)
            {
                var trialInfo = await _trialRepository.Where(t => t.Id == trialId).FirstOrDefaultAsync();
                await SendEmailHelper.SendEmailAsync(sendEmailConfig, trialInfo);
            }
        }


        public async Task<(TrialEmailNoticeConfig?, SMTPEmailConfig?)> BuildEmailConfig(Guid trialId, CriterionType criterionType, 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 && t.CriterionTypeList.Any(t => t == criterionType), ignoreQueryFilters: true)
           .Include(t => t.TrialEmailNoticeUserList).Include(t => t.TrialEmailBlackUserList).FirstOrDefaultAsync();


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

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

                //设置工作语言
                var workLanguage = isEn_us ? UserWorkLanguage.US : UserWorkLanguage.CN;


                //处理替换公司名
                htmlBodyStr = CommonEmailHelper.ReplaceCompanyName(_systemEmailConfig, htmlBodyStr, workLanguage);


                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, t.UserRole.IdentityUser.UserWorkLanguage }).ToListAsync();

                //过滤当前语言
                var toUserList = allUserList.Where(t => toUserTypeEnumList.Contains(t.UserTypeEnum)).Where(t=>t.UserWorkLanguage==workLanguage)
                   .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 (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(_localizer["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));

                    }
                }



                return (trialEmailConfig, sendEmailConfig);


            }
        }
    }
}
