using DocumentFormat.OpenXml.Spreadsheet;
using IRaCIS.Core.Domain.Share;
using IRaCIS.Core.Infrastructure;
using MailKit;
using MailKit.Security;
using MimeKit;
using NPOI.HPSF;


namespace IRaCIS.Core.Application.Helper;

public static class SendEmailHelper
{

    public static async Task SendEmailAsync(MimeMessage messageToSend, SystemEmailSendConfig _systemEmailConfig, EventHandler<MessageSentEventArgs>? messageSentSuccess = null)
    {
        try
        {
            using (var smtp = new MailKit.Net.Smtp.SmtpClient())
            {
                if (messageSentSuccess != null)
                {
                    smtp.MessageSent += messageSentSuccess;
                }


                smtp.ServerCertificateValidationCallback = (s, c, h, e) => true;

                //await smtp.ConnectAsync("smtp.qq.com", 465, SecureSocketOptions.SslOnConnect);

                //await smtp.AuthenticateAsync("zhou941003@qq.com", "sqfhlpfdvnexbcab");

                await smtp.ConnectAsync(_systemEmailConfig.Host, _systemEmailConfig.Port, SecureSocketOptions.SslOnConnect);

                await smtp.AuthenticateAsync(_systemEmailConfig.FromEmail, _systemEmailConfig.AuthorizationCode);

                await smtp.SendAsync(messageToSend);

                await smtp.DisconnectAsync(true);

            }
        }
        catch (Exception ex)
        {

            throw new BusinessValidationFailedException("邮件发送失败，您进行的操作未能成功，请检查邮箱或联系维护人员");
        }


    }

    public static async Task SendEmailAsync(SMTPEmailConfig sMTPEmailConfig, EventHandler<MessageSentEventArgs>? messageSentSuccess = null)
    {
        var messageToSend = new MimeMessage();

        //主题
        messageToSend.Subject = sMTPEmailConfig.TopicDescription;

        //发件地址
        messageToSend.From.Add(sMTPEmailConfig.FromEmailAddress);

        //收件地址

        if (sMTPEmailConfig.ToMailAddressList.Count == 0)
        {
            throw new BusinessValidationFailedException("没有收件人");
        }
        else
        {
            foreach (var item in sMTPEmailConfig.ToMailAddressList)
            {
                messageToSend.To.Add(item);
            }
            //抄送
            foreach (var copyToMailAddress in sMTPEmailConfig.CopyToMailAddressList)
            {
                messageToSend.Cc.Add(copyToMailAddress);
            }
        }

        var builder = new BodyBuilder();

        //html body

        builder.HtmlBody = sMTPEmailConfig.HtmlBodyStr;


        //附件

        foreach (var item in sMTPEmailConfig.EmailAttachMentConfigList)
        {
            //builder.Attachments.Add(item.FileName, item.FileData);

            var attachment = builder.Attachments.Add(item.FileName, item.FileStream);

            //解决附件名过长  奇怪的名字
            foreach (var param in attachment.ContentDisposition.Parameters)
                param.EncodingMethod = ParameterEncodingMethod.Rfc2047;
            foreach (var param in attachment.ContentType.Parameters)
                param.EncodingMethod = ParameterEncodingMethod.Rfc2047;

        }




        messageToSend.Body = builder.ToMessageBody();

        using (var smtp = new MailKit.Net.Smtp.SmtpClient())
        {
            if (messageSentSuccess != null)
            {
                smtp.MessageSent += messageSentSuccess;
            }


            smtp.ServerCertificateValidationCallback = (s, c, h, e) => true;

            await smtp.ConnectAsync(sMTPEmailConfig.Host, sMTPEmailConfig.Port, SecureSocketOptions.SslOnConnect);

            await smtp.AuthenticateAsync(sMTPEmailConfig.UserName, sMTPEmailConfig.AuthorizationCode);

            await smtp.SendAsync(messageToSend);

            await smtp.DisconnectAsync(true);

        }

    }
}





public class SMTPEmailConfig
{
    public int Port { get; set; }

    public string Host { get; set; }


    public string UserName { get; set; }

    public string AuthorizationCode { get; set; }


    //邮件HtmlBody

    public string HtmlBodyStr { get; set; } = string.Empty;


    //发
    public MailboxAddress FromEmailAddress { get; set; }

    //收
    public List<MailboxAddress> ToMailAddressList { get; set; } = new List<MailboxAddress>();

    //抄送
    public List<MailboxAddress> CopyToMailAddressList { get; set; } = new List<MailboxAddress>();

    //邮件主题
    public string TopicDescription { get; set; } = string.Empty;

    //邮件附件
    public List<EmailAttachMentConfig> EmailAttachMentConfigList { get; set; } = new List<EmailAttachMentConfig>() { };

}


public class EmailAttachMentConfig
{
    public string FileName { get; set; }

    public Stream FileStream { get; set; }


    public byte[] FileData { get; set; }
}
