using Amazon.Runtime.Internal.Util;
using DocumentFormat.OpenXml;
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 CommonEmailHelper
{

    /// <summary>
    /// 系统默认邮件  + 项目默认邮件  （不用添加到项目邮件配置中，才发送）
    /// </summary>
    /// <param name="configInfo"></param>
    /// <param name="messageToSend"></param>
    /// <param name="emailFunc"></param>
    /// <param name="userWorkLanguage"></param>
    /// <returns></returns>
    /// <exception cref="BusinessValidationFailedException"></exception>
    public static async Task<EmailNoticeConfig> GetEmailSubejctAndHtmlInfoAndBuildAsync(EmailNoticeConfig configInfo, MimeMessage messageToSend,
Func<(string topicStr, string htmlBodyStr), (string topicStr, string htmlBodyStr)> emailFunc, UserWorkLanguage? userWorkLanguage = null)
    {

        bool isEn_US = userWorkLanguage.HasValue ? userWorkLanguage.Value == UserWorkLanguage.US : CultureInfo.CurrentCulture.Name == StaticData.CultureInfo.en_US;

        var (topicStr, htmlBodyStr) = isEn_US ? (configInfo.EmailTopic, configInfo.EmailHtmlContent) : (configInfo.EmailTopicCN, configInfo.EmailHtmlContentCN);

        try
        {
            //每个场景修改主题 和body的逻辑不一样
            (topicStr, htmlBodyStr) = emailFunc((topicStr, htmlBodyStr));
        }
        catch (Exception ex)
        {
            //"邮件模板内容有误，填充内容出现问题，请联系运维人员核查"

            throw new BusinessValidationFailedException(I18n.T("CommonEmail_ConfigError"));
        }


        messageToSend.Subject = topicStr;

        var builder = new BodyBuilder();

        builder.HtmlBody = htmlBodyStr;

        messageToSend.Body = builder.ToMessageBody();

        return configInfo;
    }

    /// <summary>
    /// 项目手动邮件  （需要添加到项目邮件配置中，才发送）
    /// </summary>
    /// <param name="configInfo"></param>
    /// <param name="messageToSend"></param>
    /// <param name="emailFunc"></param>
    /// <param name="userWorkLanguage"></param>
    /// <returns></returns>
    /// <exception cref="BusinessValidationFailedException"></exception>
    public static async Task<TrialEmailNoticeConfig> GetTrialEmailSubejctAndHtmlInfoAndBuildAsync(TrialEmailNoticeConfig configInfo, MimeMessage messageToSend,
   Func<(string topicStr, string htmlBodyStr), (string topicStr, string htmlBodyStr)> emailFunc, UserWorkLanguage? userWorkLanguage = null)
    {

        bool isEn_US = userWorkLanguage.HasValue ? userWorkLanguage.Value == UserWorkLanguage.US : CultureInfo.CurrentCulture.Name == StaticData.CultureInfo.en_US;

        var (topicStr, htmlBodyStr) = isEn_US ? (configInfo.EmailTopic, configInfo.EmailHtmlContent) : (configInfo.EmailTopicCN, configInfo.EmailHtmlContentCN);

        try
        {
            //每个场景修改主题 和body的逻辑不一样
            (topicStr, htmlBodyStr) = emailFunc((topicStr, htmlBodyStr));
        }
        catch (Exception ex)
        {
            //"邮件模板内容有误，填充内容出现问题，请联系运维人员核查"

            throw new BusinessValidationFailedException(I18n.T("CommonEmail_ConfigError"));
        }


        messageToSend.Subject = topicStr;

        var builder = new BodyBuilder();

        builder.HtmlBody = htmlBodyStr;

        messageToSend.Body = builder.ToMessageBody();

        return configInfo;
    }

    public static string ReplacePlatformName(SystemEmailSendConfig _systemEmailConfig, string needDealtxt, UserWorkLanguage? userWorkLanguage = null)
    {
        var isEn_US = userWorkLanguage.HasValue ? userWorkLanguage.Value == UserWorkLanguage.US : CultureInfo.CurrentCulture.Name == StaticData.CultureInfo.en_US;

        var platformName = isEn_US ? _systemEmailConfig.PlatformName : _systemEmailConfig.PlatformNameCN;

        var str = needDealtxt.Replace("{platformName}", platformName);
        return str;
    }


    public static string ReplaceCompanyName(SystemEmailSendConfig _systemEmailConfig, string needDealtxt, UserWorkLanguage? userWorkLanguage = null)
    {
        var isEn_US = userWorkLanguage.HasValue ? userWorkLanguage.Value == UserWorkLanguage.US : CultureInfo.CurrentCulture.Name == StaticData.CultureInfo.en_US;

        var str = needDealtxt.Replace("{company}", isEn_US ? _systemEmailConfig.CompanyName : _systemEmailConfig.CompanyNameCN)
            .Replace("{company abbreviation}", isEn_US ? _systemEmailConfig.CompanyShortName : _systemEmailConfig.CompanyShortNameCN);
        return str;
    }

    /// <summary>
    /// 翻译字典
    /// </summary>
    /// <param name="inDto"></param>
    /// <returns></returns>
    public static async Task<List<string>> TranslationDictionary(TranslationDictionaryDto inDto)
    {

        var dictionaryCodelist = inDto.DictionaryList.Select(x => x.DictionaryCode).ToList();

        var enumValueList = inDto.DictionaryList.Select(x => x.EnumValue).ToList();


        var dicList = await inDto.DictionaryRepository.Where(x => dictionaryCodelist.Contains(x.Parent.Code) && enumValueList.Contains(x.Code)).Select(x => new DictionaryData()
        {

            DictionaryCode = x.Parent.Code,
            EnumValue = x.Code,
            Value = x.Value,
            ValueCN = x.ValueCN
        }).ToListAsync();


        List<string> result = new List<string>();

        inDto.DictionaryList.ForEach(x =>
        {

            var dic = dicList.Where(y => y.EnumValue == x.EnumValue && y.DictionaryCode.Equals(x.DictionaryCode,StringComparison.OrdinalIgnoreCase)).FirstOrDefault();
            result.Add(dic == null ? string.Empty : (inDto.IsEn_US ? dic.Value : dic.ValueCN));
        });

        return result;



    }
}


/// <summary>
/// 转换字典的Dto
/// </summary>
public class TranslationDictionaryDto
{
    /// <summary>
    /// 字典仓储
    /// </summary>
    public IRepository<Dictionary> DictionaryRepository { get; set; }

    /// <summary>
    /// 是否是英文
    /// </summary>
    public bool IsEn_US { get; set; }

    /// <summary>
    /// 字典
    /// </summary>
    public List<DictionaryDto> DictionaryList { get; set; } = new List<DictionaryDto>();



}

/// <summary>
/// 字典对象
/// </summary>
public class DictionaryDto
{
    /// <summary>
    /// 字典Code
    /// </summary>
    public string DictionaryCode { get; set; }

    /// <summary>
    /// 枚举值
    /// </summary>
    public string EnumValue { get; set; }
}


public class DictionaryData
{
    /// <summary>
    /// 字典Code
    /// </summary>
    public string DictionaryCode { get; set; }

    /// <summary>
    /// 枚举值
    /// </summary>
    public string EnumValue { get; set; }

    /// <summary>
    /// 值
    /// </summary>
    public string Value { get; set; }


    /// <summary>
    /// 返回
    /// </summary>
    public string ValueCN { get; set; }
}
