package com.vetti.common.utils.email;

import com.vetti.common.config.TwilioConfig;
import com.vetti.common.entity.verification.BaseTemplateEmail;
import com.vetti.common.utils.MessageUtils;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.sendgrid.Method;
import com.sendgrid.Request;
import com.sendgrid.Response;
import com.sendgrid.SendGrid;
import com.sendgrid.helpers.mail.Mail;
import com.sendgrid.helpers.mail.objects.Content;
import com.sendgrid.helpers.mail.objects.Email;
import com.sendgrid.helpers.mail.objects.Personalization;
import com.vetti.common.utils.StringUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;

/**
 * @author ID
 * @date 2025/8/29 22:36
 */
@Component
public class EmailUtil {

    @Resource
    private TwilioConfig twilioConfig;

    /**
     * 发邮件
     *
     * @param toEmail
     * @param subject
     * @param content
     * @throws IOException
     */
    public void sendEmail(String toEmail, String subject, String content) throws IOException {
        Email from = new Email(twilioConfig.getFromEmail(), twilioConfig.getFromName());
        Email to = new Email(toEmail);
        Content emailContent = new Content("text/plain", content);
        Mail mail = new Mail(from, subject, to, emailContent);

        SendGrid sg = new SendGrid(twilioConfig.getApiKey());
        Request request = new Request();

        request.setMethod(Method.POST);
        request.setEndpoint("mail/send");
        request.setBody(mail.build());

        Response response = sg.api(request);

        // 可以根据响应状态做进一步处理
        if (response.getStatusCode() >= 400) {
            throw new RuntimeException(MessageUtils.messageCustomize("systemEmailUtil10001")+": " + response.getBody());
        }
    }

    public void sendEmail(String toEmail, String templateId, BaseTemplateEmail templateEmail) throws IOException {
        Email from = new Email(twilioConfig.getFromEmail(), twilioConfig.getFromName());
        Email to = new Email(toEmail);
        Content emailContent = new Content("text/html", " ");

        // 关键修改：使用无参构造函数，避免自动创建Personalization
        Mail mail = new Mail();
        mail.setFrom(from); // 手动设置发件人
        mail.addContent(emailContent); // 手动添加内容

        // 处理模板和个性化配置（此时只会添加一个Personalization）
        template(to, mail, templateId, templateEmail);

        SendGrid sg = new SendGrid(twilioConfig.getApiKey());
        Request request = new Request();
        request.setMethod(Method.POST);
        request.setEndpoint("mail/send");
        request.setBody(mail.build());
        Response response = sg.api(request);

        if (response.getStatusCode() >= 400) {
            throw new RuntimeException(MessageUtils.messageCustomize("systemEmailUtil10001")+": " + response.getBody());
        }
    }

    private void template(Email to, Mail mail, String templateId, BaseTemplateEmail templateEmail) {
        mail.setTemplateId(templateId);
        Personalization personalization = new Personalization();
        personalization.addTo(to); // 仅添加一次收件人

        // 处理模板变量
        JsonObject jsonO = templateEmail.toJsonObject();
        if (jsonO != null) {
            jsonO.entrySet().forEach(entry -> {
                String key = entry.getKey();
                JsonElement value = entry.getValue();
                if (value.isJsonPrimitive()) {
                    if (value.getAsJsonPrimitive().isString()) {
                        personalization.addDynamicTemplateData(key, value.getAsString());
                    } else if (value.getAsJsonPrimitive().isNumber()) {
                        personalization.addDynamicTemplateData(key, value.getAsNumber());
                    } else if (value.getAsJsonPrimitive().isBoolean()) {
                        personalization.addDynamicTemplateData(key, value.getAsBoolean());
                    }
                } else {
                    System.out.printf("键: %s, 非基本类型值: %s%n", key, value);
                }
            });
        }

        // 仅添加一次Personalization
        mail.addPersonalization(personalization);
    }

    /**
     * 使用 em7941.routez.app 域名发送模板邮件
     */
    public void sendEmailByEm7941(String toEmail, String templateId, BaseTemplateEmail templateEmail) throws IOException {

        Email from = new Email(twilioConfig.getFromEmailEm7941(), twilioConfig.getFromNameEm7941());
        Email to = new Email(toEmail);
        Content emailContent = new Content("text/html", " ");

        Mail mail = new Mail();
        mail.setFrom(from);
        mail.addContent(emailContent);
        if (StringUtils.isNotEmpty(twilioConfig.getReplyToEm7941())) {
            mail.setReplyTo(new Email(twilioConfig.getReplyToEm7941()));
        }

        template(to, mail, templateId, templateEmail);

        SendGrid sg = new SendGrid(twilioConfig.getApiKey());
        Request request = new Request();
        request.setMethod(Method.POST);
        request.setEndpoint("mail/send");
        request.setBody(mail.build());
        Response response = sg.api(request);

        if (response.getStatusCode() >= 400) {
            throw new RuntimeException(MessageUtils.messageCustomize("systemEmailUtil10001")+": " + response.getBody());
        }
    }

}
