using IRaCIS.Core.Application.Helper;
using IRaCIS.Core.Application.MassTransit.Command;
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.Text;
using System.Threading.Tasks;

namespace IRaCIS.Core.Application.MassTransit.Consumer;

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

    /// <summary>
    ///  加急的医学反馈任务  通知MIM
    /// </summary>
    /// <param name="context"></param>
    /// <returns></returns>
    /// <exception cref="NotImplementedException"></exception>
    public async Task Consume(ConsumeContext<UrgentMedicalReviewAddedEvent> context)
    {
        Console.WriteLine("发送【加急的医学反馈任务  通知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 criterion = await _readingQuestionCriterionTrialRepository.FirstOrDefaultAsync(x => x.Id == medicalReview.VisitTask.TrialReadingCriterionId);
        var userinfo = await _userRepository.Where(x => x.Id == medicalReview.MedicalManagerUserId).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 messageToSend = new MimeMessage();
        //发件地址
        messageToSend.From.Add(new MailboxAddress(_systemEmailConfig.FromName, _systemEmailConfig.FromEmail));
        messageToSend.To.Add(new MailboxAddress(String.Empty, userinfo.EMail));

        var trialInfo = await _trialRepository.FirstOrDefaultAsync(t => t.Id == medicalReview.TrialId);
        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= "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(), }
            }
         }) ;

            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),
                   userinfo.FullName,              // 用户名
                   trialInfo.ExperimentName,        // 项目
                   criterion.CriterionName,  // 阅片标准
                   taskInfo.BlindSubjectCode.IsNullOrEmpty() ? taskInfo.Subject.Code : taskInfo.BlindSubjectCode, // 受试者
                   taskInfo.TaskBlindName,             // 访视
                   dictionValue[0],      // 任务类型
                   dictionValue[1],     // 阅片人是否同意
                   dictionValue[2],     // 审核状态
                   dictionValue[3]    // 是否加急
                    );

                return (topicStr, htmlBodyStr);
            };

        await CommonEmailHelper.GetEmailSubejctAndHtmlInfoAndBuildAsync(_emailNoticeConfigrepository, EmailBusinessScenario.SiteSurveyReject, messageToSend, emailConfigFunc);

        await SendEmailHelper.SendEmailAsync(messageToSend, _systemEmailConfig);
    }
}

//IR 回复医学反馈通知MIM
public class UrgentIRRepliedMedicalReviewConsumer : IConsumer<UrgentIRRepliedMedicalReview>
{
    public Task Consume(ConsumeContext<UrgentIRRepliedMedicalReview> context)
    {
        throw new NotImplementedException();
    }
}

/// <summary>
/// MIM 回复医学返回通知IR
/// </summary>
public class UrgentMIMRepliedMedicalReviewConsumer : IConsumer<UrgentMIMRepliedMedicalReview>
{
    public Task Consume(ConsumeContext<UrgentMIMRepliedMedicalReview> context)
    {
        throw new NotImplementedException();
    }
}

/// <summary>
/// 加急阅片 IR 申请重阅  或者PM 申请重阅
/// </summary>
public class UrgentIRApplyedReReadingConsumer : IConsumer<UrgentApplyedReReading>
{
    public Task Consume(ConsumeContext<UrgentApplyedReReading> context)
    {
        throw new NotImplementedException();
    }
}

