package com.iformall.service.msg.impl;

import com.iformall.domain.po.WxMsgValidationcodeModel;
import com.iformall.domain.po.msg.BaseMsg;
import com.iformall.domain.po.msg.MailMsg;
import com.iformall.enums.EnumMsgOpen;
import com.iformall.mapper.WxMsgModelMapper;
import com.iformall.mapper.WxMsgValidationcodeModelMapper;
import com.iformall.service.msg.MsgSendService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.util.List;
import java.util.Map;

/**
 * 发送邮件
 * @author luozukai
 * @date 2019/3/7 16:03
 */
@Service
public class SendEmailServiceImpl implements MsgSendService {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private JavaMailSender sender;
    @Value("${spring.mail.username}")
    private String from;
    @Autowired
    private WxMsgModelMapper wxMsgModelMapper;
    @Autowired
    private WxMsgValidationcodeModelMapper wxMsgValidationcodeModelMapper;

    @Override
    public void send(BaseMsg baseMsg) throws Exception{
        MailMsg mailMsg = (MailMsg)baseMsg;
        //根据模板替换动态内容
        if(mailMsg.getModelId() != null){
            WxMsgValidationcodeModel msgModel = new WxMsgValidationcodeModel();
            msgModel.setTenantId(mailMsg.getTenantId());
            msgModel.setType(mailMsg.getModelType());
            msgModel.setModelId(mailMsg.getModelId());
            msgModel.setOpen(EnumMsgOpen.OPEN.getCode());
            List<WxMsgValidationcodeModel> modelList = wxMsgValidationcodeModelMapper.findList(msgModel);
            if(CollectionUtils.isEmpty(modelList)){
                throw new Exception("模板id:"+mailMsg.getModelId()+"不存在");
            }
            WxMsgValidationcodeModel wxMsgModel = modelList.get(0);

            String msg = wxMsgModel.getContent();
            for (Map.Entry<String, String> entry : mailMsg.getDynamicContentMap().entrySet()) {
                msg = msg.replace("{"+entry.getKey()+"}", entry.getValue());
            }
            if(StringUtils.isNotBlank(wxMsgModel.getEmailBgImg())){
                msg = msg.replace("{bg}", wxMsgModel.getEmailBgImg());
            }
            mailMsg.setMsg(msg);
        }

        if(mailMsg.isHtml()){ //html邮件
            MimeMessage message = sender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(mailMsg.getTo());
            helper.setSubject(mailMsg.getSubject());
            helper.setText(mailMsg.getMsg(), true);

            sender.send(message);
        }else if(StringUtils.isNotBlank(mailMsg.getFilePath())){
            MimeMessage message = sender.createMimeMessage();
            String filePath = mailMsg.getFilePath();
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(mailMsg.getTo());
            helper.setSubject(mailMsg.getSubject());
            helper.setText(mailMsg.getMsg(), true);

            FileSystemResource file = new FileSystemResource(new File(filePath));
            String fileName = filePath.substring(filePath.lastIndexOf(File.separator));
            helper.addAttachment(fileName, file);

            sender.send(message);
        }else if(StringUtils.isNotBlank(mailMsg.getRscI()) && StringUtils.isNotBlank(mailMsg.getRscPath())){
            MimeMessage message = sender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(mailMsg.getTo());
            helper.setSubject(mailMsg.getSubject());
            helper.setText(mailMsg.getMsg(), true);

            FileSystemResource res = new FileSystemResource(new File(mailMsg.getRscPath()));
            helper.addInline(mailMsg.getRscI(), res);

            sender.send(message);
        }else{
            SimpleMailMessage message = new SimpleMailMessage();
            message.setFrom(from);
            message.setTo(mailMsg.getTo());
            message.setSubject(mailMsg.getSubject());
            message.setText(mailMsg.getMsg());
            sender.send(message);
        }
    }
}
