package com.example.system.controller;
import com.example.system.model.ArticleTable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import com.example.system.repository.ArticleRepository;
import com.example.system.repository.RegistrationRepository;
import org.springframework.web.bind.annotation.RestController;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.List;
import java.util.Optional;
import java.util.Properties;
import org.springframework.web.bind.annotation.CrossOrigin;

@RestController
@CrossOrigin
@RequestMapping("/api")
@Component
public final class EmailController {
    @Autowired
    private RegistrationRepository registrationRepository;

    @Autowired
    private ArticleRepository articleRepository;

    @PostMapping("/sendemail")
    public ResponseEntity<String> sendemail(@RequestParam Long competitionId, @RequestParam Integer articleId) {
        Optional<ArticleTable> articleOpt = articleRepository.findById(articleId);
        if (articleOpt.isEmpty()) {
            return new ResponseEntity<>("未找到公告", HttpStatus.NOT_FOUND);
        }
        ArticleTable article = articleOpt.get();
        List<String> emails = registrationRepository.findompetitionemailId(competitionId);
        if (emails.isEmpty()) {
            return new ResponseEntity<>("未寻找到参加比赛的用户", HttpStatus.NOT_FOUND);
        }
        String briefContent = article.getBriefContent();
        String articleTitle = article.getArticleTitle();
        for (String email : emails) {
            if (email != null && !email.isEmpty()) {
                boolean sendStatus = sendMail(email, "您参加的 ["+articleTitle+"] 比赛有新的公告内容：\n" + briefContent +"\n请前往镐京学院竞赛管理平台官网查看。", "比赛公告");
                if (!sendStatus) {
                    System.out.println("Failed to send email to: " + email);
                }
            }
        }
        return new ResponseEntity<>("邮件发送成功", HttpStatus.OK);
    }

    @Value("${mail.user}")
    private String USER; // 发件人邮箱地址

    @Value("${mail.password}")
    private String PASSWORD; // 如果是qq邮箱可以使户端授权码

    /**
     * 发送邮件
     * @param to 收件人邮箱
     * @param text 邮件正文
     * @param title 标题
     */
    public boolean sendMail(String to, String text, String title){
        try {
            final Properties props = new Properties();
            props.put("mail.smtp.auth", "true");
            props.put("mail.smtp.host", "smtpdm.aliyun.com"); // 请根据你的邮箱服务商替换为相应的地址

            // 发件人的账号
            props.put("mail.user", "shuguang@email.92wap.cn");
            //发件人的密码
            props.put("mail.password", "LIUSHUguang520");

            Authenticator authenticator = new Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    String userName = props.getProperty("mail.user");
                    String password = props.getProperty("mail.password");
                    return new PasswordAuthentication(userName, password);
                }
            };
            Session mailSession = Session.getInstance(props, authenticator);

            MimeMessage message = new MimeMessage(mailSession);
            String username = props.getProperty("mail.user");
            InternetAddress form = new InternetAddress(username);
            message.setFrom(form);

            InternetAddress toAddress = new InternetAddress(to);
            message.setRecipient(Message.RecipientType.TO, toAddress);

            message.setSubject(title);

            message.setContent(text, "text/html;charset=UTF-8");

            Transport.send(message);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
}
