package com.mvc.utils;

import com.mvc.constant.BaseConstant;
import com.mvc.entity.TAiread;
import com.mvc.model.CustomizeGroupModel;
import com.mvc.model.TAireadModel;
import com.mvc.netty.dealconstant.ResourceTag;
import com.mvc.service.copy.TAireadService;
import com.mvc.service.taizhang.CustomizeGroupService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.annotation.Resource;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.util.ByteArrayDataSource;
import java.io.File;
import java.io.FileInputStream;
import java.io.UnsupportedEncodingException;
import java.util.Date;

/**
 * 消息通知(邮件)
 */
@Component
public class NotifyUtil {
    private Logger log = LoggerFactory.getLogger(NotifyUtil.class);

    public static boolean mIsSend = false;
    //在自来水公司测试的三台设备SN号，遇到这三台，要进行邮件提醒
    //public static String mDeviceSns = "00000003241,00000003237,00000003236";
    public static String mZLSGroupId = "5cc88f214e014e90bf10f036a378aada";

    private final String EMAIL_FROM_USER = "support@xzeai.com";                 //邮件-发件人
    private final String EMAIL_AUTHORIZE_CODE = "iLx7u44yqGSKJZQo";             //邮件-授权码

    private final String EMAIL_TO_USER = "365984181@qq.com";                    //邮件-收件人
    private final String EMAIL_CC_USER = "870892757@qq.com";                    //邮件-抄送人
    ////private final String EMAIL_TO_USER = "15097911597@163.com";                    //邮件-收件人(测试)

    private final String EMAIL_BCC_USER = "";                                   //邮件-密送人

    private final String EMAIL_FROM_NICKNAME = "鸿成鑫鼎";                          //邮件-发件人昵称

    /*//测试的邮箱
    private final String EMAIL_TO_USER = "870892757@qq.com";//邮件-收件人
    private final String EMAIL_AUTHORIZE_CODE = "VZVKUDYADRLVWFFA";            //163邮件-授权码
    private final String EMAIL_CC_USER = "g_zhao@sohu.com,15097911597@139.com";//邮件-抄送人
    private final String EMAIL_BCC_USER = "guozhao888@sina.cn";//邮件-密送人*/

    @Resource
    private TAireadService tAireadService;

    @Resource
    private CustomizeGroupService customizeGroupService;

    @Resource
    private Environment env;

    public void sendEMail(TAireadModel tAireadModel) {
        if (!mIsSend) {//推送开关
            return;
        }

        CustomizeGroupModel customizeGroupModel = customizeGroupService.findCustomizeGroupByGroupId(mZLSGroupId);
        if (customizeGroupModel == null || !customizeGroupModel.getStationCodes().contains(tAireadModel.getStationCode())) {
            return;
        }

        if (StringUtils.isEmpty(tAireadModel.getSzsbz())) {//大图没有
            TAireadModel smallModel = tAireadService.findTairedBySnAndTime(tAireadModel.getStationCode(), tAireadModel.getSampleTime(), 1);
            if (smallModel != null) {
                tAireadModel.setSzsbz(smallModel.getSzsbz());
                tAireadModel.setSzsbgl(smallModel.getSzsbgl());
            }
        }
        StringBuilder sbMsg = new StringBuilder();
        String[] arr = tAireadModel.getSzsbz().split(",");

        if (arr != null && arr.length > 11) {
            if (BaseConstant.IDENT_GOOD_FLAG.contains(arr[11])) {//符合1278,不发送
                log.info("符合1278,不推送[" + tAireadModel.getDeviceSn() + "]");
            } else {
                sbMsg.append("不符合1278规则;");
            }
        }

        if (DateUtil.getMinutes(tAireadModel.getSampleTime()) != 0) {
            sbMsg.append("采样时间不是整点;");
        }
        Date temp = DateUtil.getOtherDateByMinute(tAireadModel.getSampleTime(), -1);
        TAiread lastTAiread = tAireadService.findlastTAireadBydatatime(tAireadModel.getStationCode(), temp);
        if (lastTAiread != null && lastTAiread.getResultValue().compareTo(tAireadModel.getResultValue()) > 0) {
            sbMsg.append("识别结果小于前一次值;");
        }

        if (sbMsg.length() == 0) {
            return;
        }
        log.info("自来水邮件提醒SN:" + tAireadModel.getDeviceSn() + ":" + sbMsg);
        // 获取默认session对象
        Session session = JavaMailUntil.createSession(EMAIL_FROM_USER, EMAIL_AUTHORIZE_CODE);
        try {
            // 创建默认的 MimeMessage 对象
            MimeMessage message = new MimeMessage(session);
            //防止成为垃圾邮件，披上outlook的马甲
            message.addHeader("X-Mailer", "Microsoft Outlook Express 6.00.2900.2869");
            // 发送人
            message.setFrom(new InternetAddress(EMAIL_FROM_USER, EMAIL_FROM_NICKNAME, "UTF-8"));
            // 接收人
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(EMAIL_TO_USER));
            //抄送
            if (StringUtils.isNotEmpty(EMAIL_CC_USER)) {
                message.addRecipients(Message.RecipientType.CC, InternetAddress.parse(EMAIL_CC_USER));
            }
            //密送
            if (StringUtils.isNotEmpty(EMAIL_BCC_USER)) {
                message.addRecipients(Message.RecipientType.BCC, InternetAddress.parse(EMAIL_BCC_USER));
            }

            // 标题
            message.setSubject("自来水公司设备:[" + tAireadModel.getDeviceSn() + "]" + sbMsg);
            // 消息体
            //Multipart multipart = getMultipart(tAireadModel);//内容复杂容易判定垃圾邮件
            Multipart multipart = null;
            if (multipart != null && (tAireadModel.getBigJpgUrl().contains(".jpg") || tAireadModel.getBigJpgUrl().contains(".bmp"))) {//带图
                message.setContent(multipart);
            } else {//纯文本
                StringBuilder sb = new StringBuilder();
                sb.append("SN:");
                sb.append(tAireadModel.getDeviceSn());
                sb.append(" ");
                sb.append(sbMsg);
                sb.append(";采样时间:");
                sb.append(DateUtil.formateDate(tAireadModel.getSampleTime(), DateUtil.PATTERN_DATA_NORMAL));
                message.setContent(sb.toString(), "text/html;charset=utf-8");
            }

            // 发送消息
            Transport transport = session.getTransport();
            transport.connect(EMAIL_FROM_USER, EMAIL_AUTHORIZE_CODE);

            //sendMessage 是不使用收件人和抄送人,直接接收人
            //transport.sendMessage(message, InternetAddress.parse(toUser));

            //send方法时,发送人和抄送人,才有作用
            transport.send(message);
            transport.close();

            System.out.println("Sent message successfully....");
        } catch (MessagingException | UnsupportedEncodingException e) {
            e.printStackTrace();
            log.error("邮件发送异常", e);
        }
    }

    /*•554 DT:SPM 发送的邮件内容包含了未被许可的信息，或被系统识别为垃圾邮件。请检查是否有用户发送病毒或者垃圾邮件；**
      •554 DT:SUM 信封发件人和信头发件人不匹配；
      •554 IP is rejected, smtp auth error limit exceed 该IP验证失败次数过多，被临时禁止连接。请检查验证信息设置；
      •554 HL:IHU 发信IP因发送垃圾邮件或存在异常的连接行为，被暂时挂起。请检测发信IP在历史上的发信情况和发信程序是否存在异常；
      •554 HL:IPB 该IP不在网易允许的发送地址列表里；
      •554 MI:STC 发件人当天内累计邮件数量超过限制，当天不再接受该发件人的投信。请降低发信频率；
      •554 MI:SPB 此用户不在网易允许的发信用户列表里；
      •554 IP in blacklist 该IP不在网易允许的发送地址列表里
     */

    /** ------------------------- 太原煤气报警通知 ------------------------- */
    /**
     * 发送邮件
     *
     * @param toUser  收件人
     * @param subject 主题
     * @param content 内容
     */
    public void sendEMail(String toUser, String subject, String content) {
        sendEMail(toUser, subject, content, (DataSource) null, null);
    }

    /**
     * 发送邮件(本地附件)
     *
     * @param toUser       收件人
     * @param subject      主题
     * @param content      正文
     * @param fileFullName 文件名(含路径)
     */
    public void sendEMail(String toUser, String subject, String content, String fileFullName) {
        DataSource source = null;
        File file = new File(fileFullName);
        if (file.isFile() && file.exists()) {
            source = new FileDataSource(fileFullName);
        }
        sendEMail(toUser, subject, content, source, file.getName());
    }

    /**
     * 发送邮件(附件byte[])
     *
     * @param toUser   收件人
     * @param subject  主题
     * @param content  正文
     * @param fileData 文件数据
     * @param fileName 文件名(不含路径,作为附件的文件名)
     */
    public void sendEMail(String toUser, String subject, String content, byte[] fileData, String fileName) {
        DataSource source = new ByteArrayDataSource(fileData, "application/octet-stream");
        sendEMail(toUser, subject, content, source, fileName);
    }

    private void sendEMail(String toUser, String subject, String content, DataSource dataSource, String fileName) {
        // 获取默认session对象
        Session session = JavaMailUntil.createSession(EMAIL_FROM_USER, EMAIL_AUTHORIZE_CODE);
        try {
            // 创建默认的 MimeMessage 对象
            MimeMessage message = new MimeMessage(session);
            //防止成为垃圾邮件，披上outlook的马甲
            message.addHeader("X-Mailer", "Microsoft Outlook Express 6.00.2900.2869");
            // 发送人
            message.setFrom(new InternetAddress(EMAIL_FROM_USER, EMAIL_FROM_NICKNAME, "UTF-8"));
            // 接收人
            if(toUser.contains(";")){//多人接收
                InternetAddress[] toInternetAddresses = getInternetAddresses(toUser);
                message.setRecipients(Message.RecipientType.TO, toInternetAddresses);
            }else {//单人接收
                message.addRecipient(Message.RecipientType.TO, new InternetAddress(toUser));
            }

            // 标题
            message.setSubject(subject);

            // 消息体
            message.setContent(content, "text/html;charset=utf-8");

            // 发送消息
            Transport transport = session.getTransport();
            transport.connect(EMAIL_FROM_USER, EMAIL_AUTHORIZE_CODE);

            if (dataSource != null && StringUtils.isNotEmpty(fileName)) {
                // 添加附件
                MimeBodyPart messageBodyPart = new MimeBodyPart();
                Multipart multipart = new MimeMultipart();

                messageBodyPart = new MimeBodyPart();
                messageBodyPart.setDataHandler(new DataHandler(dataSource));
                messageBodyPart.setFileName(fileName);
                multipart.addBodyPart(messageBodyPart);

                // 设置MIME类型为混合
                message.setContent(multipart);
            }

            //send方法时,发送人和抄送人,才有作用
            transport.send(message);
            transport.close();

            System.out.println("Sent message successfully....");
        } catch (MessagingException | UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    /**
     * 根据toUser,获取InternetAddress数组
     *
     * @param toUser
     * @return
     * @throws UnsupportedEncodingException
     */
    private InternetAddress[] getInternetAddresses(String toUser) throws UnsupportedEncodingException {
        String[] toAddresses = toUser.split(";");
        InternetAddress[] internetAddresses = new InternetAddress[toAddresses.length];
        for (int i = 0; i < toAddresses.length; i++) {
            internetAddresses[i] = new InternetAddress(toAddresses[i], toAddresses[i], "UTF-8");
        }
        return internetAddresses;
    }

    //带图片的(有图片在发件时可能就被判定为垃圾,而发不出去 SMTPSendFailedException: 554 DT:SPM 163)
    private Multipart getMultipart(TAireadModel tAireadModel) {
        try {
            Multipart multipart = new MimeMultipart();
            StringBuilder sb = new StringBuilder();
            sb.append("<h1>");
            sb.append("设备号:");
            sb.append(tAireadModel.getDeviceSn());
            sb.append("</h1>");
            sb.append("<p><img src=\"cid:img01\"></p>");
            //添加text:
            BodyPart textpart = new MimeBodyPart();
            //textpart.setContent("<h1>Hello</h1><p><img src=\"cid:img01\"></p>", "text/html;charset=utf-8");
            textpart.setContent(sb.toString(), "text/html;charset=utf-8");
            multipart.addBodyPart(textpart);

            String fileName = tAireadModel.getBigJpgUrl();
            fileName = StringUtils.isEmpty(fileName) ? tAireadModel.getSmallJpgUrl() : fileName;
            if (StringUtils.isEmpty(fileName)) {
                return multipart;
            }
            fileName = ImageUtil.convertImageUrlToLocalPath(fileName,env.getProperty(ResourceTag.UploadPathTag.getTag()));//将url转换为本地路径

            File file = new File(fileName);
            if (file.exists()) {//如果文件存在时，添加内嵌图片
                //添加image:
                BodyPart imagepart = new MimeBodyPart();
                imagepart.setFileName(file.getName());
                imagepart.setDataHandler(new DataHandler(new ByteArrayDataSource(new FileInputStream(fileName), "application/octet-stream")));
                multipart.addBodyPart(imagepart);

                //设置当前image为内嵌图片
                //这个ID和HTML中引用的ID对应起来，邮件客户端就可以正常显示内嵌图片
                imagepart.setHeader("Content-ID", "<img01>");
            }
            return multipart;

        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }
}
