package com.lanyuanxiaoyao.digtal.market.sender

import com.lanyuanxiaoyao.digtal.market.MailProperties
import jakarta.activation.DataHandler
import jakarta.mail.Message
import jakarta.mail.Part
import jakarta.mail.internet.InternetAddress
import jakarta.mail.internet.MimeBodyPart
import jakarta.mail.internet.MimeMultipart
import jakarta.mail.internet.MimeUtility
import jakarta.mail.util.ByteArrayDataSource
import java.net.SocketException
import org.springframework.mail.javamail.JavaMailSender
import org.springframework.retry.support.RetryTemplate

class MailSender(private val mailProperties: MailProperties, private val javaMailSender: JavaMailSender) : Sender {
    override fun send(title: String, content: Map<String, Any>) {
        val screenshotData = content["screenshot"] as ByteArray
        val tableData = content["table"] as String
        RetryTemplate.builder()
            .withTimeout(600000)
            .fixedBackoff(10000)
            .notRetryOn(SocketException::class.java)
            .build()
            .run {
                javaMailSender.send(
                    javaMailSender.createMimeMessage().also { message ->
                        message.subject = title
                        message.addRecipients(Message.RecipientType.TO, mailProperties.targets.map { InternetAddress(it) }.toTypedArray())
                        message.setContent(MimeMultipart().also { multipart ->
                            multipart.addBodyPart(MimeBodyPart().also { mimeBodyPart ->
                                mimeBodyPart.setContent(
                                    // language=HTML
                                    "<h1>ODS 数据同步监控</h1>\n<b>如有异常请联系相关人员处理</b>\n<br/>\n${tableData}\n",
                                    "text/html;charset=UTF-8"
                                )
                            })
                            multipart.addBodyPart(MimeBodyPart().also { mimeBodyPart ->
                                mimeBodyPart.disposition = Part.ATTACHMENT
                                mimeBodyPart.fileName = MimeUtility.encodeText("screenshot.png")
                                mimeBodyPart.dataHandler = DataHandler(ByteArrayDataSource(screenshotData, "image/png"))
                            })
                        })
                        message.saveChanges()
                    }
                )
            }
    }
}