package com.liquidnet.service.adam.config;


import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.OptimisticLockerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.liquidnet.service.adam.util.EmailUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.mail.NoSuchProviderException;
import java.util.Properties;

@Configuration
public class UtilBeanConfig {

    //发件邮箱
    @Value("${liquidnet.conf.email.sender.host}")
    private String myEmailAccount;
    //邮箱密码
    @Value("${liquidnet.conf.email.sender.password}")
    private String myEmailPassword;
    //smtp地址
    @Value("${liquidnet.conf.email.sender.smtp}")
    private String myEmailSMTPHost;

    @Bean
    public EmailUtil initEmailUtil() throws NoSuchProviderException {
        EmailUtil emailUtil = new EmailUtil();
        Properties props = new Properties();

        props.setProperty("mail.transport.protocol", "smtp");   // 使用的协议（JavaMail规范要求）
//        props.setProperty("mail.smtp.host", myEmailSMTPHost);   // 发件人的邮箱的 SMTP 服务器地址
//        props.setProperty("mail.smtp.auth", "true");            // 需要请求认证
//        props.put("mail.smtp.starttls.enable", "true");
//        props.put("mail.smtp.port", "587");
        gmailssl(props);

        emailUtil.setMyEmailAccount(myEmailAccount);
        emailUtil.setMyEmailPassword(myEmailPassword);
        emailUtil.setMyEmailSMTPHost(myEmailSMTPHost);
        emailUtil.setProps(props);

        return emailUtil;
    }

    /**
     * gmail邮箱SSL方式
     */
    private void gmailssl(Properties props) {
        final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
        props.put("mail.debug", "true");
        props.put("mail.smtp.host", "smtp.gmail.com");
        props.put("mail.smtp.ssl.enable", "true");
        props.put("mail.smtp.socketFactory.class", SSL_FACTORY);
        props.put("mail.smtp.port", "465");
        props.put("mail.smtp.socketFactory.port", "465");
        props.put("mail.smtp.auth", "true");
    }


    /**
     * gmail邮箱的TLS方式
     * @param props
     */
    private void gmailtls(Properties props) {
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.host", "smtp.gmail.com");
        props.put("mail.smtp.port", "587");
    }

    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return interceptor;
    }

    @Bean
    public OptimisticLockerInterceptor optimisticLockerInterceptor() {
        return new OptimisticLockerInterceptor();
    }
}
