package com.yeejoin.amos.avic.face.service;

import com.sun.mail.util.MailSSLSocketFactory;
import com.yeejoin.amos.avic.face.model.AvicEMailModel;
import com.yeejoin.amos.avic.face.model.EMailModel;
import com.yeejoin.amos.avic.face.orm.dao.AvicEMailMapper;
import com.yeejoin.amos.avic.face.orm.entity.AvicEMail;
import com.yeejoin.amos.feign.systemctl.model.DictionarieValueModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.DependsOn;
import org.springframework.stereotype.Component;
import org.typroject.tyboot.core.rdbms.service.BaseService;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.io.File;
import java.io.FileOutputStream;
import java.security.GeneralSecurityException;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import java.util.UUID;


@Component
@DependsOn("systemctl")
public class EMailSenderService extends BaseService<AvicEMailModel,AvicEMail, AvicEMailMapper>{

	private Transport transport;

	@Autowired
	private EMailModel eMailModel;

	public EMailSenderService() throws Exception {
	    //初始化该类拿不到配置文件里的东西
		//init(eMailModel.getHost(), eMailModel.getPort(), eMailModel.getUsername(), eMailModel.getPassword(), eMailModel.isValipwd(), eMailModel.isEnabledStarttls());
	}

    public void start(List<DictionarieValueModel> result) throws Exception{

        eMailModel.setHost(result.get(0).getDictDataValue());
        eMailModel.setPort(Integer.parseInt(result.get(1).getDictDataValue()));
        eMailModel.setUsername(result.get(2).getDictDataValue());
        eMailModel.setPassword(result.get(3).getDictDataValue());
        init(eMailModel.getHost(), eMailModel.getPort(), eMailModel.getUsername(), eMailModel.getPassword(), eMailModel.isValipwd(), eMailModel.isEnabledStarttls());
    }

    public void init(String host, int port, final String username, final String password, boolean valipwd , boolean enabledStarttls) throws Exception {

        Properties props = System.getProperties();

        props.put("mail.smtp.host", host);
        props.put("mail.smtp.port", port);

        if (enabledStarttls) {
            MailSSLSocketFactory sf = null;
            try {
                sf = new MailSSLSocketFactory();
            } catch (GeneralSecurityException e) {
                throw e;
            }
            sf.setTrustAllHosts(true);
            props.put("mail.smtp.ssl.socketFactory", sf);
            props.put("mail.smtp.starttls.enable", "true");
        }

        if (valipwd) {
            props.put("mail.smtp.auth", true);
        } else {
            props.put("mail.smtp.auth", false);
        }

        Session session = Session.getInstance(props, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password);
            }
        });
        URLName urlName = new URLName("smtp",host,port,null,null,null);
        this.transport = session.getTransport(urlName);
    }

    private void doSend(MimeMessage mimeMessage, Address[] addresses) throws MessagingException {
        transport.connect();
        transport.sendMessage(mimeMessage, addresses);
        transport.close();
    }


    public void send(String avicCode, String targetAddress, String text, String file) throws Exception {
    	MimeMessage mimeMessage = new MimeMessage(Session.getInstance(new Properties()));

        mimeMessage.setFrom(new InternetAddress(targetAddress));
        mimeMessage.setRecipients(Message.RecipientType.TO, new Address[]{
                new InternetAddress(targetAddress, avicCode)
        });

        mimeMessage.setSubject(11111111 + UUID.randomUUID().toString());
        mimeMessage.setSentDate(new Date());
        mimeMessage.setHeader("X-Mailer", "LOTONtechEmail");
        mimeMessage.setHeader("usercode_header", "xUnMI9FGtWvuFYjHZAlWdmjh58sWfyZOOJNa+HwaJfELrqMvJg3iuIjRAhpuccf5");
        MimeBodyPart mbp1 = new MimeBodyPart();

        mbp1.setText(text);
        Multipart mp = new MimeMultipart();
        mimeMessage.setContent(mp);
        mimeMessage.writeTo(new FileOutputStream(new File("D:\\temp.eml")));

        for (int i = 0; i < 1; i++) {
            doSend(mimeMessage, new Address[]{
                    new InternetAddress("ccc<user4@test.com>"),
            });
        }
    }

    public String getEmailTemplate() {
    	List<AvicEMailModel> list = this.queryForList(null, false);
    	for (AvicEMailModel model : list) {
    		if (model.getEnabled() == 1) {
    			return model.getTemplate();
    		}
    	}
    	return "";
    }
}
