xinyb
6 天以前 ee2316e2cb7afde1c54f5e4216a1b0d1e055749e
src/com/yc/crm/mail/service/MailImpl.java
@@ -1,34 +1,23 @@
package com.yc.crm.mail.service;
import com.sun.mail.imap.IMAPStore;
import com.yc.action.grid.GridUtils;
import com.yc.crm.mail.entity.T482102Entity;
import com.yc.crm.mail.entity.t482101HEntity;
import com.yc.crm.base.entity.T482115Entity;
import com.yc.crm.mail.action.MailFolder;
import com.yc.crm.mail.action.MailTag;
import com.yc.crm.mail.entity.*;
import com.yc.entity.AttachmentConfig;
import com.yc.entity.attachment.AttachmentEntity;
import com.yc.entity.attachment.AttachmentWhereEntity;
import com.yc.factory.FactoryBean;
import com.yc.sdk.shopping.service.imagedata.ShoppingImageDataIfc;
import com.yc.sdk.weixincp.util.UploadFiles;
import com.yc.service.BaseService;
import com.yc.service.upload.AttachmentIfc;
import com.yc.utils.SessionKey;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.mail.*;
import javax.mail.internet.*;
import javax.mail.search.FlagTerm;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import java.util.regex.Pattern;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
/**
 * @BelongsProject: eCoWorksV3
@@ -39,35 +28,45 @@
 */
@Service
public class MailImpl extends BaseService implements MailIfc {
    @Autowired
    MailAccountIfc emailAccountIfc;
    @Autowired
    ShoppingImageDataIfc imgData;
    @Autowired
    MailTagIfc mailTagIfc;
    @Autowired
    MailFolderIfc mailFolderIfc;
    final static String shoppingImageServer = AttachmentConfig.get("attachment.server");
    @Transactional(rollbackFor = Exception.class)
    @Override
    public t482101HEntity saveReceivingMail(t482101HEntity m) {
        String sql = "set nocount on\n";
        try {
            if(StringUtils.isBlank(m.getDocCode())) {
                sql += "declare @docCode varchar(50) \n";
            if (StringUtils.isBlank(m.getDocCode())) {
                sql += "declare @docCode varchar(50) ,@unid varchar(50),@fieldId varchar(100),@originalFileName varchar(100)," +
                        "@physicalFile varchar(50),@OriginalPicture varbinary(max) \n";
                sql += "exec sp_newdoccode 482101," + GridUtils.prossSqlParm(m.getUserCode()) + ",@docCode output \n";
                sql += "insert into t482101H(companyId,companyName,formId,docCode,docdate,PeriodID,postCode,postname,mailType,sender,receiver,cc,bcc,subject,userCode,userName,content,file_unid) values ";
                sql += "insert into t482101H(companyId,companyName,formId,docCode,docdate,PeriodID,postCode,postname,mailType,senderName,sender,sender_time,receiver,receiving_time," +
                        "cc,bcc,subject,userCode,userName,content,plain_text,messageId,read_flag,delete_flag,create_time,update_time," +//receive_time
                        "attach_flag,attachment_list) values ";
                sql += "(" + GridUtils.prossSqlParm(m.getCompanyId()) + "," + GridUtils.prossSqlParm(m.getCompanyName()) + ",482101," +
                        "@docCode,convert(varchar(10),getdate(),120),convert(varchar(7),getdate(),120),"
                        + GridUtils.prossSqlParm(m.getUserCode()) + "," + GridUtils.prossSqlParm(m.getUserName()) + "," +
                        +m.getMailType() + "," + GridUtils.prossSqlParm(m.getSender()) + "," +
                        GridUtils.prossSqlParm(m.getReceiver()) + "," + GridUtils.prossSqlParm(m.getCc()) + "," + GridUtils.prossSqlParm(m.getBcc()) + "," +
                        +m.getMailType() + "," + GridUtils.prossSqlParm(m.getSenderName()) + "," + GridUtils.prossSqlParm(m.getSender()) + "," + GridUtils.prossSqlParm(m.getSenderTime()) + "," +
                        GridUtils.prossSqlParm(StringUtils.join(m.getReceiver(), ",")) + "," + GridUtils.prossSqlParm(m.getReceivingTime()) + "," + GridUtils.prossSqlParm(StringUtils.join(m.getCc(), ",")) + "," +
                        GridUtils.prossSqlParm(StringUtils.join(m.getBcc(), ",")) + "," +
                        GridUtils.prossSqlParm(m.getSubject()) + "," + GridUtils.prossSqlParm(m.getUserCode()) + "," + GridUtils.prossSqlParm(m.getUserName()) + "," +
                        GridUtils.prossSqlParm(m.getContent()) + "," + GridUtils.prossSqlParm(m.getFileUNID()) + ") \n";
                        GridUtils.prossSqlParm(m.getContent()) + "," + GridUtils.prossSqlParm(m.getPlainText()) + "," + GridUtils.prossSqlParm(m.getMessageId()) + "," +
                        m.getReadFlag() + "," + m.getDeleteFlag() + ",getdate(),getdate()," + m.getAttachFlag() + "," + GridUtils.prossSqlParm(m.getAttachmentList()) + ") \n" +
                        mailFileSql(m.getMailFile());
                sql += "select @docCode as docCode";
                String docCode = jdbcTemplate.queryForObject(sql, String.class);
                if (StringUtils.isNotBlank(docCode)) {
                    m.setDocCode(docCode);
                }
            }else{
            } else {
                updateReceivingMail(m);//修改
            }
            return m;
@@ -76,62 +75,137 @@
        }
    }
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveReceivingMailList(List<t482101HEntity> mail) {
    public String saveReceivingMailList(List<t482101HEntity> mail) {
        String sql = "set nocount on\n";
        try {
            sql += "declare @docCode varchar(50) \n";
            sql += "declare @docCode varchar(50) ,@unid varchar(50),@fieldId varchar(100),@originalFileName varchar(100),@docCodeList varchar(3000)=''," +
                    "@physicalFile varchar(50),@OriginalPicture varbinary(max) \n";
            for (t482101HEntity m : mail) {//遍历内容
                sql += "exec sp_newdoccode 482101," + GridUtils.prossSqlParm(m.getUserCode()) + ",@docCode output \n";
                sql += "insert into t482101H(companyId,companyName,formId,docCode,docdate,PeriodID,postCode,postname,mailType,sender,receiver,cc,bcc,subject,userCode,userName,content,file_unid) values ";
                sql += " select @docCodeList=@docCodeList+@docCode+';'\n" +//返回单号
                        "insert into t482101H(companyId,companyName,formId,docCode,docdate,PeriodID,postCode,postname,mailType,senderName,sender,sender_time,receiver,receiving_time," +
                        "cc,bcc,subject,userCode,userName,content,plain_text,messageId,read_flag,delete_flag,create_time,update_time," +
                        "attach_flag,attachment_list) values ";
                sql += "(" + GridUtils.prossSqlParm(m.getCompanyId()) + "," + GridUtils.prossSqlParm(m.getCompanyName()) + ",482101," +
                        "@docCode,convert(varchar(10),getdate(),120),convert(varchar(7),getdate(),120),"
                        + GridUtils.prossSqlParm(m.getUserCode()) + "," + GridUtils.prossSqlParm(m.getUserName()) + "," +
                        +m.getMailType() + "," + GridUtils.prossSqlParm(m.getSender()) + "," +
                        GridUtils.prossSqlParm(m.getReceiver()) + "," + GridUtils.prossSqlParm(m.getCc()) + "," + GridUtils.prossSqlParm(m.getBcc()) + "," +
                        +m.getMailType() + "," + GridUtils.prossSqlParm(m.getSenderName()) + "," + GridUtils.prossSqlParm(m.getSender()) + "," + GridUtils.prossSqlParm(m.getSenderTime()) + "," +
                        GridUtils.prossSqlParm(StringUtils.join(m.getReceiver(), ",")) + "," + GridUtils.prossSqlParm(m.getReceivingTime()) + "," + GridUtils.prossSqlParm(StringUtils.join(m.getCc(), ",")) + "," +
                        GridUtils.prossSqlParm(StringUtils.join(m.getBcc(), ",")) + "," +
                        GridUtils.prossSqlParm(m.getSubject()) + "," + GridUtils.prossSqlParm(m.getUserCode()) + "," + GridUtils.prossSqlParm(m.getUserName()) + "," +
                        GridUtils.prossSqlParm(m.getContent()) + "," + GridUtils.prossSqlParm(m.getFileUNID()) + ") \n";
//                sql +="exec postt482101V3 '' ,'',''";
                        GridUtils.prossSqlParm(m.getContent()) + "," + GridUtils.prossSqlParm(m.getPlainText()) + "," + GridUtils.prossSqlParm(m.getMessageId()) + "," +
                        m.getReadFlag() + "," + m.getDeleteFlag() + ",getdate(),getdate()," + m.getAttachFlag() + "," + GridUtils.prossSqlParm(m.getAttachmentList()) + ") \n" +
                        mailFileSql(m.getMailFile());
            }
            jdbcTemplate.update(sql);
            return jdbcTemplate.queryForObject(sql + "\n select @docCodeList", String.class);
        } catch (Exception e) {
            throw e;
        }
    }
    /**
     * 邮件附件的处理
     *
     * @param mailFile
     * @return
     */
    private String mailFileSql(MailFileEntity mailFile) {
        if (mailFile == null) {//附件保存
            return "";
        }
        String sql = "";
        String originalFileName = "";
        String fileType = "";
        try {
            for (MailFileEntity.MailBodyPart file : mailFile.getPart()) {
                originalFileName = file.getFileName();
                fileType = file.getFileType();
                sql += "select @unid=" + GridUtils.prossSqlParm(mailFile.getUnId()) + "\n" +
                        ",@fieldId=" + GridUtils.prossSqlParm(file.getFieldId()) + "\n" +
                        ",@originalFileName=" + GridUtils.prossSqlParm(originalFileName) + "\n" +
                        ",@physicalFile=" + GridUtils.prossSqlParm(file.getPhysicalFile()) + "\n" +
                        ",@OriginalPicture=" + UploadFiles.byteToHexString(file.getByteFile()) + "\n";
                sql += "insert into _sys_Attachment(unId,formId,docCode,fieldId,physicalFile,originalFileName,FileSize,fileType,UploadTime,LastUpdateTime,OriginalPicture) values ";
                sql += " (@unid,482101,@docCode,@fieldId,@physicalFile,@originalFileName," + file.getFileSize() + "," + GridUtils.prossSqlParm(fileType) + ",getdate(),getdate(),@OriginalPicture) \n";
            }
            return sql;
        } catch (Exception e) {
            return "";
        }
    }
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Integer updateReceivingMail(t482101HEntity mail) {
        String sql = "set nocount on\n";
        try {
            sql += "update t482101H set sender=" + GridUtils.prossSqlParm(mail.getSender()) + ",receiver=" + GridUtils.prossSqlParm(mail.getReceiver()) + "," +
                    "cc=" + GridUtils.prossSqlParm(mail.getCc()) + ",bcc=" + GridUtils.prossSqlParm(mail.getBcc()) + ",subject=" + GridUtils.prossSqlParm(mail.getSubject()) + "," +
                    "content=" + GridUtils.prossSqlParm(mail.getContent()) + ",file_unid=" + GridUtils.prossSqlParm(mail.getFileUNID()) + ",mailType=" + mail.getMailType() + "," +
                    "updateTime=getdate() \n";
            sql += " where docCode=" + GridUtils.prossSqlParm(mail.getDocCode());
            sql += "select select @@ROWCOUNT";
            return jdbcTemplate.update(sql, Integer.class);
            sql += "update t482101H set sender=" + GridUtils.prossSqlParm(mail.getSender()) + ",receiver=" + GridUtils.prossSqlParm(StringUtils.join(mail.getReceiver(), ",")) + "," +
                    "cc=" + GridUtils.prossSqlParm(StringUtils.join(mail.getCc(), ",")) + ",bcc=" + GridUtils.prossSqlParm(StringUtils.join(mail.getBcc(), ",")) + ",subject=" + GridUtils.prossSqlParm(mail.getSubject()) + "," +
                    "content=" + GridUtils.prossSqlParm(mail.getContent()) + ",attachment_list=" + GridUtils.prossSqlParm(mail.getAttachmentList()) + ",mailType=" + mail.getMailType() + "," +
                    "update_time=getdate() \n";
            sql += " where docCode=" + GridUtils.prossSqlParm(mail.getDocCode()) + "\n";
            sql += "select @@ROWCOUNT";
            return jdbcTemplate.queryForObject(sql, Integer.class);
        } catch (Exception e) {
            throw e;
        }
    }
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Integer updateDeleteFlag(String userCode, String docCode) {
        String sql = "set nocount on\n";
        try {
            sql += "declare @docCode varchar(200) ='" + docCode + "' \n";
            sql += "update t482101H deleteFlag=1 where userCode =" + GridUtils.prossSqlParm(userCode) +
                    " and docCode in (select list from GetInStr(@docCode))\n";//标记删除
            sql += " select @@ROWCOUNT";
            return jdbcTemplate.queryForObject(sql, Integer.class);
        } catch (Exception e) {
            throw e;
        }
    }
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Integer deleteEmail(String userCode, String docCode) {
        String sql = "set nocount on\n";
        try {
            sql += "declare @docCode varchar(200) ='" + docCode + "' \n";
            sql += "update t482101H deleteFlag=1 where userCode =" + GridUtils.prossSqlParm(userCode) +
                    " and docCode in (select list from GetInStr(@docCode))\n";//标记删除
            sql += " select @@ROWCOUNT";
            return jdbcTemplate.queryForObject(sql, Integer.class);
        } catch (Exception e) {
            throw e;
        }
    }
    @Override
    public Integer deleteReceivingMail(String docCode) {
    public Integer deleteEmail(String messageId) {
        String sql = "set nocount on\n";
        try {
            sql += "update t482101H deleteFlag=1 where docCode=" + GridUtils.prossSqlParm(docCode) + "\n";//标记为已删除
            sql += "select select @@ROWCOUNT";
            return jdbcTemplate.update(sql, Integer.class);
            sql += "declare @messageId varchar(200) ='" + messageId + "' \n";
            sql += " delete t482101H where messageId in (select list from GetInStr(@messageId))\n";//删除
            sql += " select @@ROWCOUNT";
            return jdbcTemplate.queryForObject(sql, Integer.class);
        } catch (Exception e) {
            throw e;
        }
    }
    @Override
    public t482101HEntity getReceivingMailInfo(String email, String docCode) {
    public t482101HEntity getReceivingMailInfo(String docCode) {
        String sql = "set nocount on\n";
        try {
            sql += "select top 1 DocCode,sender,receiver,subject,content,file_unid as fileUNID from t482101H where receiver = '" + email + "' and docCode=" + GridUtils.prossSqlParm(docCode);
            sql += "select top 1 DocCode,companyId,companyName,senderName,senderName,sender,receiver,mailType,subject,content,plain_text,file_unid as fileUNID,messageId," +
                    "read_flag,delete_flag,attach_flag,urgent_flag,receipt_flag,track_flag,userCode,userName,create_time,update_time," +
                    "send_status,receive_time,sign_id,attachment_list,remark,remark,sender_time,receiving_time," +
                    "(case when (isnull(handle_time,'') <> '' and isnull(handle_time,'') < getdate()) then 1 else 0 end) as handle,handle_time," +
                    "DocVersion from t482101H " +
                    "where docCode=" + GridUtils.prossSqlParm(docCode);
            return jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(t482101HEntity.class)).get(0);
        } catch (Exception e) {
            throw e;
@@ -139,361 +213,326 @@
    }
    @Override
    public List<t482101HEntity> getReceivingMailList(String email, Integer mailType, boolean isNoRead) {
    public List<t482101HList> getReceivingMailList(String email, Integer mailType, boolean isNoRead, String userCode, Integer page, Integer limit) {
        String sql = "set nocount on\n";
        try {
            sql += "select DocCode,sender,receiver,subject,content,file_unid as fileUNID " +
                    "from t482101H ";
            if (isNoRead) {//未读执行
                sql += "where receiver ='" + email + "' and  isnull(readFlag,0)= 0";
            } else {//已读
                sql += "where receiver ='" + email + "' and  mailType=" + mailType;
            sql += "select companyId,companyName,mailType,DocCode,senderName,sender,receiver,subject,plain_text," +
                    "receive_time,update_time,create_time,senderName,sender,userCode,userName,folder_id,delete_Flag,attachment_list," +
                    "read_Flag,(case when (isnull(handle_time,'') <> '' and isnull(handle_time,'') < getdate()) then 1 else 0 end) as handle," +
                    "handle_time,sender_time,receiving_time from t482101H ";
            sql += " where userCode=" + GridUtils.prossSqlParm(userCode);
            sql += " and mailType=" + mailType;//0:草稿箱 1:收件箱 2:发件箱
            if (StringUtils.isNotBlank(email)) {
                if (mailType == 1) {
                    sql += " and receiver like '%" + email + "%'";
                } else if (mailType == 2) {
                    sql += " and sender =" + GridUtils.prossSqlParm(email);
                }
            }
            return jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(t482101HEntity.class));
            if (isNoRead) {//0表示未读,1表示已读
                sql += " and isnull(read_flag,0) = 0";
            }
            sql += " order by docCode asc \n";
            sql += " OFFSET (" + page + " - 1) * " + limit + " ROWS FETCH NEXT " + limit + " ROWS ONLY";
            return jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(t482101HList.class));
        } catch (Exception e) {
            throw e;
        }
    }
    @Override
    public List<t482101HEntity> getMailReceiving(T482102Entity emailEntity, HttpServletRequest request) throws MessagingException {
        String imapServer = emailEntity.getReceiveHost();//"imap.qq.com";
        String user = emailEntity.getEmail();//"xxx@qq.com";
        String pwd = emailEntity.getPassword();//"xxxx";
        HashMap IAM = new HashMap();
        //带上IMAP ID信息,由key和value组成,例如name,version,vendor,support-email等。
        IAM.put("name", emailEntity.getAliasEmail());
        IAM.put("version", emailEntity.getDocVersion() + "");
        IAM.put("vendor", emailEntity.getCompanyName());
        IAM.put("support-email", emailEntity.getEmail());
        //创建会话
        Session session = Session.getInstance(new Properties(), new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(user, pwd);
            }
        });
        //存储对象
        IMAPStore store = (IMAPStore) session.getStore(emailEntity.getReceiveProtocol());//imap协议或pop3协议类型(推荐你使用IMAP协议来存取服务器上的邮件。)
        //连接
        store.connect(imapServer, user, pwd);
        store.id(IAM);//163邮箱需要,不然会报:A3 NO SELECT Unsafe Login. Please contact kefu@188.com for help
        Folder folder = null;
        try {
            // 获得收件箱
            folder = store.getFolder("INBOX");
            // 以读写模式打开收件箱
            folder.open(Folder.READ_WRITE);
            //false 表示未读
            FlagTerm flagTerm = new FlagTerm(new Flags(Flags.Flag.SEEN), true);
            //获得收件箱的邮件列表
            Message[] messages = folder.search(flagTerm);
            //返回邮箱封装内容
            return setMailContent(messages, request);
        } catch (NoSuchProviderException e) {
            throw e;
        } catch (MessagingException e) {
            throw e;
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            try {
                if (folder != null) {
                    folder.close(false);
                }
                if (store != null) {
                    store.close();
                }
            } catch (MessagingException e) {
                throw e;
            }
        }
    }
    @Override
    public void sendingMail(t482101HEntity t482101H, HttpServletRequest request) throws Exception {
    public List<t482101HList> getHandleMailList(String email, String userCode, Integer page, Integer limit) {
        String sql = "set nocount on\n";
        try {
            //根据当前用户查询绑定的邮箱信息
            T482102Entity emailEntity = emailAccountIfc.getAccountInfo(t482101H.getUserCode(), t482101H.getSender());//返回邮箱的账号信息
            if (emailEntity == null || StringUtils.isBlank(emailEntity.getEmail())) {
                throw new Exception("找不到邮箱:" + t482101H.getSender() + "配置信息,请完善:" + t482101H.getSender() + "邮箱配置在尝试发送邮件");
            }
            //邮箱服务器配置
            Properties properties = new Properties();
            properties.setProperty("mail.smtp.host", emailEntity.getSmtpHost());
            properties.setProperty("mail.smtp.port", emailEntity.getSmtpPort() + "");
            properties.setProperty("mail.smtp.auth", "true");
            properties.setProperty("mail.smtp.starttls.enable", "true");
            //
            String sendEmail = emailEntity.getEmail();//发件人
            String sendPassword = emailEntity.getPassword();//密码
            String recipientEmail = t482101H.getReceiver();//收件人
            Session session = Session.getInstance(properties, new Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(sendEmail, sendPassword);
                }
            });
            MimeMessage message = new MimeMessage(session);
            message.setFrom(new InternetAddress(sendEmail));
            message.setRecipient(Message.RecipientType.TO, new InternetAddress(recipientEmail));
            message.setSubject(t482101H.getSubject());
            if (StringUtils.isNotBlank(t482101H.getCc())) {//抄送
                String[] cc = t482101H.getCc().split(";");
                message.setRecipients(Message.RecipientType.CC, InternetAddress.parse(StringUtils.join(cc, ",")));
            }
            if (StringUtils.isNotBlank(t482101H.getBcc())) {//密送
                String[] bcc = t482101H.getBcc().split(";");
                message.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(StringUtils.join(bcc, ",")));
            }
            //创建多部分消息
            Multipart multipart = new MimeMultipart();
            MimeBodyPart textPart = new MimeBodyPart();
            textPart.setText(t482101H.getContent());//内容
            multipart.addBodyPart(textPart);
            //下面附件内容
            if (StringUtils.isNotBlank(t482101H.getFileUNID())) {//有附件内容
                String[] fileUnId = t482101H.getFileUNID().split(";");//第一个必定是unId值
                AttachmentIfc attachmentIfc = (AttachmentIfc) FactoryBean.getBean("AttachmentImpl");
                //获取到附件内容
                List<AttachmentEntity> attachmentEntities = attachmentIfc.getAttachmentEntityList(fileUnId[0]);
                if (attachmentEntities != null && attachmentEntities.size() > 0) {
                    for (AttachmentEntity a : attachmentEntities) {
                        if (Arrays.asList(fileUnId).contains(a.getSeq() + "")) {//是附件对应的seq才处理
                            InputStream inputStream = new ByteArrayInputStream(a.getOriginalPicture());
                            File file = new File(a.getOriginalFileName());
                            FileUtils.copyInputStreamToFile(inputStream, file);
                            MimeBodyPart bodyPart = new MimeBodyPart();
                            bodyPart.attachFile(file);
                            bodyPart.setFileName(a.getOriginalFileName());
                            multipart.addBodyPart(bodyPart);
                        }
                    }
                }
            }
            message.setContent(multipart);
            try {
                Transport.send(message);//发送
            } catch (MessagingException m) {//异常处理
                t482101H.setMailType(0);//草稿箱状态
                updateMailDrafts(t482101H);//更新成草稿箱
                throw new Exception("发送邮件异常,邮件已保存在草稿箱。异常原因:" + m.getCause() != null ? m.getCause().getMessage() : m.getMessage());
            }
            sql += "select companyId,companyName,mailType,DocCode,senderName,sender,receiver,subject,plain_text," +
                    "receive_time,update_time,create_time,senderName,sender,userCode,userName,folder_id,delete_Flag, " +
                    "read_Flag,(case when (isnull(handle_time,'') <> '' and isnull(handle_time,'') < getdate()) then 1 else 0 end) as handle," +
                    "handle_time,sender_time,receiving_time from t482101H ";
            sql += " where isnull(handle_time,'') <> '' and isnull(handle_time,'') < getdate()";
            sql += " and userCode=" + GridUtils.prossSqlParm(userCode) + " and receiver like '%" + email + "%'";
            sql += " order by docCode asc \n";
            sql += " OFFSET (" + page + " - 1) * " + limit + " ROWS FETCH NEXT " + limit + " ROWS ONLY";
            return jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(t482101HList.class));
        } catch (Exception e) {
            throw e;
        }
    }
    @Override
    public List<t482101HList> getFolderMailList(String type, String userCode, Integer page, Integer limit) throws Exception {
        String sql = "set nocount on\n";
        try {
            String[] id = type.split("_");
            if (id.length != 2) {
                throw new Exception("邮件类型Id格式不正确");
            }
            sql += "select companyId,companyName,mailType,DocCode,senderName,sender,receiver,subject,plain_text," +
                    "receive_time,update_time,create_time,senderName,sender,userCode,userName,folder_id,delete_Flag, " +
                    "read_Flag,(case when (isnull(handle_time,'') <> '' and isnull(handle_time,'') < getdate()) then 1 else 0 end) as handle," +
                    "handle_time,sender_time,receiving_time from t482101H ";
            sql += " where userCode=" + GridUtils.prossSqlParm(userCode) + " \n";
            if (id[0].equals("folder")) {//是文件夹
                sql += " and folder_id=" + id[1] + " \n";
            } else if (id[0].equals("tag")) {//是标签
                sql += " and tag_list like '%," + id[1] + ",%'";
            }
            sql += " order by docCode asc \n";
            sql += " OFFSET (" + page + " - 1) * " + limit + " ROWS FETCH NEXT " + limit + " ROWS ONLY";
            return jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(t482101HList.class));
        } catch (Exception e) {
            throw e;
        }
    }
    @Override
    public List<t482101HList> getUserMailList(String userCode) {
        String sql = " set nocount on \n";
        try {
            sql = "select a.DocCode,isnull(a.mailType,0) as mailType,isnull(a.read_flag,0) as read_flag,a.sender,a.receiver, " +
                    "(case when (isnull(handle_time,'') <> '' and isnull(handle_time,'') < getdate()) then 1 else 0 end) as handle " +
                    " from t482101H a where  a.userCode=" + GridUtils.prossSqlParm(userCode) + " order by a.mailType";
            return jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(t482101HList.class));
        } catch (Exception e) {
            throw e;
        }
    }
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Integer updateMailDrafts(t482101HEntity mail) {
        String sql = "set nocount on\n";
        try {
            sql += "update t482101H set sender=" + GridUtils.prossSqlParm(mail.getSender()) + ",receiver=" + GridUtils.prossSqlParm(mail.getReceiver()) + "," +
                    "cc=" + GridUtils.prossSqlParm(mail.getCc()) + ",bcc=" + GridUtils.prossSqlParm(mail.getBcc()) + ",subject=" + GridUtils.prossSqlParm(mail.getSubject()) + "," +
                    "content=" + GridUtils.prossSqlParm(mail.getContent()) + ",file_unid=" + GridUtils.prossSqlParm(mail.getFileUNID()) + ",mailType=" + mail.getMailType() + "," +
                    "updateTime=getdate() \n";
            sql += "update t482101H set sender=" + GridUtils.prossSqlParm(mail.getSender()) + ",receiver=" + GridUtils.prossSqlParm(StringUtils.join(mail.getReceiver(), ",")) + "," +
                    "cc=" + GridUtils.prossSqlParm(StringUtils.join(mail.getCc(), ",")) + ",bcc=" + GridUtils.prossSqlParm(StringUtils.join(mail.getBcc(), ",")) + "," +
                    "subject=" + GridUtils.prossSqlParm(mail.getSubject()) + ",messageId=" + GridUtils.prossSqlParm(mail.getMessageId()) + "," +
                    "content=" + GridUtils.prossSqlParm(mail.getContent()) + ",attachment_list=" + GridUtils.prossSqlParm(mail.getAttachmentList()) + ",mailType=" + mail.getMailType() + "," +
                    "update_time=getdate() \n";
            sql += " where docCode=" + GridUtils.prossSqlParm(mail.getDocCode());
            sql += "select select @@ROWCOUNT";
            return jdbcTemplate.update(sql, Integer.class);
            sql += " select @@ROWCOUNT";
            return jdbcTemplate.queryForObject(sql, Integer.class);
        } catch (Exception e) {
            throw e;
        }
    }
    @Override
    public Integer deleteMailDrafts(String docCode) {
    public List<String> getMessageIdList(String receiver) {
        List<String> messageId = null;
        String sql = " set nocount on \n";
        try {
            sql += "select messageId from t482101H where receiver='" + receiver + "'";
            List<t482101HEntity> message = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(t482101HEntity.class));
            if (message != null && message.size() > 0) {
                messageId = new ArrayList<>();
                messageId = message.stream().map(t482101HEntity::getMessageId).distinct().collect(Collectors.toList());//去重
            }
            return messageId;
        } catch (Exception e) {
            throw e;
        }
    }
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateRead(String docCode, boolean status) {
        String sql = " set nocount on \n";
        try {
            sql += "declare @docCode varchar(200) ='" + docCode + "' \n";
            sql += "update t482101H set read_flag=" + (status ? 1 : 0) + " where docCode in (select list from GetInStr(@docCode))\n";
            sql += "select @@ROWCOUNT";
            jdbcTemplate.queryForObject(sql, Integer.class);
        } catch (Exception e) {
            throw e;
        }
    }
    @Override
    public void updateMailType(String docCode, Integer folderId, String tagId) {
        String sql = " set nocount on \n";
        try {
            boolean bol = false;
            sql += "declare @docCode varchar(200) ='" + docCode + "' \n";
            sql += "update t482101H set \n";
            if (!folderId.equals(0)) {
                sql += " folder_id=" + folderId + "\n";
                bol = true;
            }
            if (StringUtils.isNotBlank(tagId)) {
                sql += (bol ? "," : "") + " tag_list='," + tagId + ",' \n";
            }
            sql += " where docCode in (select list from GetInStr(@docCode))\n";
            sql += "select @@ROWCOUNT";
            jdbcTemplate.queryForObject(sql, Integer.class);
        } catch (Exception e) {
            throw e;
        }
    }
    @Override
    public List<MailModuleEntity> getMailModuleList(String userCode) {
        List<MailModuleEntity> module = MailModuleEntity.setMailInitial();
        try {
            List<T482102Entity> account = emailAccountIfc.getAccount(userCode);//获取这个账号绑定的邮箱
            List<t482101HList> userMail = getUserMailList(userCode);
            for (MailModuleEntity m : module) {
                List<t482101HList> mailTypeList = null;
                int mailType = m.getMailType();//类型
                switch (mailType) {
                    case 0://草稿箱
                    case 1://收件箱
                    case 2://发件箱
                        if (mailType == 0) {
                            m.setChildren(new ArrayList<>());
                            if (userMail.size() > 0) {
                                m.setTotal((int) userMail.stream().filter(s -> s.getMailType().equals(mailType)).count());
                            }
                        } else {
                            List<MailModuleEntity.MailCode> codeList = new ArrayList<>();
                            MailModuleEntity.MailCode code = new MailModuleEntity.MailCode();
                            code.setKey(mailType == 1 ? "InboxPage1" : "IndexPage1");
                            code.setMailType(mailType);
                            code.setMailName(mailType == 1 ? "全部收件" : "全部发件");
                            codeList.add(code);
                            if (account.size() == 0) {//没有直接跳过
                                m.setChildren(codeList);
                                continue;
                            }
                            int allCount = 0;
                            int count = 0;
                            for (T482102Entity a : account) {
                                MailModuleEntity.MailCode nextCode = new MailModuleEntity.MailCode();
                                String eMail = (mailType == 1 ? a.getReceiveEmail() : a.getSmtpEmail());//获取邮箱账号
                                nextCode.setKey(mailType == 1 ? "receiver" : "sender");
                                nextCode.setMailName(eMail);
                                nextCode.setMailType(m.getMailType());
//                                if (userMail.size() > 0) {
//                                    count = (mailType == 1 ? (int) userMail.stream().filter(s -> s.getMailType().equals(mailType) && s.getReceiver().contains(eMail)).count() :
//                                            (int) userMail.stream().filter(s -> s.getMailType().equals(mailType) && s.getSender().contains(eMail)).count());
//                                    nextCode.setTotal(count);
//                                }
                                if (mailType == 1) {//是收件箱,统计未读数量
                                    count = (int) userMail.stream().filter(s -> s.getMailType().equals(mailType) && s.getReceiver().contains(eMail) && s.getReadFlag().equals(0)).count();
                                    nextCode.setTotal(count);
                                }
                                codeList.add(nextCode);
                                allCount = (allCount + count);
                            }
                            codeList.get(0).setTotal(allCount);
                            m.setTotal(allCount);
                            m.setChildren(codeList);
                        }
                        break;
                    case 3://待处理邮件
                        m.setChildren(new ArrayList<>());
                        if (userMail.size() > 0) {
                            m.setTotal((int) userMail.stream().filter(s -> s.getHandle().equals(1)).count());
                        }
                        break;
                    case 4://未读邮件
                        m.setChildren(new ArrayList<>());
                        if (userMail.size() > 0) {
                            m.setTotal((int) userMail.stream().filter(s -> s.getReadFlag().equals(0)).count());
                        }
                        break;
                    case 5://群邮箱
                        m.setChildren(new ArrayList<>());
                        break;
                    default:
                        break;
                }
            }
            return module;
        } catch (Exception e) {
            throw e;
        }
    }
    @Override
    public List<MailModuleBelowEntity> getMailModuleBelowList(String userCode) {
        List<MailModuleBelowEntity> below = MailModuleBelowEntity.setMailInitial();
        try {
            for (MailModuleBelowEntity b : below) {
                String key = b.getKey();
                if (key.equals("moduleBelowA")) {//文件夹
                    List<T482107Entity> t482107 = mailFolderIfc.getMailFolder(userCode);
                    b.setList(MailFolder.getFolderModule(t482107, ""));
                }
                if (key.equals("moduleBelowB")) {//标签邮件
                    List<T482115Entity> tag = mailTagIfc.getTagList(userCode, "", -1);
                    b.setList(MailTag.getTagModule(tag));
                }
                if (key.equals("moduleBelowC")) {//显示更多
                    List<MailModuleBelowEntity> CList = new ArrayList<>();
                    MailModuleBelowEntity delete = new MailModuleBelowEntity();
                    delete.setKey("deleteMail");
                    delete.setName("已删除邮件");
                    CList.add(delete);
                    MailModuleBelowEntity waste = new MailModuleBelowEntity();
                    waste.setKey("wasteMail");
                    waste.setName("垃圾邮件");
                    CList.add(waste);
                    MailModuleBelowEntity track = new MailModuleBelowEntity();
                    track.setKey("trackMail");
                    track.setName("追踪信息");
                    CList.add(track);
                    b.setList(CList);
                }
            }
            return below;
        } catch (Exception e) {
            throw e;
        }
    }
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateMailHandle(String handleTime, String docCode) {
        String sql = " set nocount on \n";
        try {
            sql += "declare @docCode varchar(200) ='" + docCode + "' \n";
            sql += "update t482101H set handle_time=" + (StringUtils.isBlank(handleTime) ? "null" : GridUtils.prossSqlParm(handleTime)) +
                    " where docCode in (select list from GetInStr(@docCode))\n";
            sql += "select @@ROWCOUNT";
            jdbcTemplate.queryForObject(sql, Integer.class);
        } catch (Exception e) {
            throw e;
        }
    }
    @Override
    public Integer getMailTotal(String email, Integer mailType, boolean isNoRead, String id, String userCode) {
        String sql = "set nocount on\n";
        try {
            sql += "delete t482101H where docCode=" + GridUtils.prossSqlParm(docCode);
            sql += "select select @@ROWCOUNT";
            return jdbcTemplate.update(sql, Integer.class);
        } catch (Exception e) {
            throw e;
        }
    }
    /**
     * 收件箱返回的信息进行封装处理
     *
     * @param messages
     * @return
     * @throws MessagingException
     * @throws IOException
     */
    public List<t482101HEntity> setMailContent(Message[] messages, HttpServletRequest request) throws Exception {
        try {
            List<t482101HEntity> t482101HEntityList = new ArrayList<>();
            HttpSession session = request.getSession();
            Message m = null;
            for (int i = 0; i < messages.length; i++) {
                m = messages[i];
                String from = MimeUtility.decodeText(m.getFrom()[0].toString());
                InternetAddress internetAddress = new InternetAddress(from);
                t482101HEntity mail = new t482101HEntity();
                if (m.isSet(Flags.Flag.SEEN)) {
//                    System.out.println("邮件已标记为已读。");
                    mail.setReadFlag(1);//已读
                } else {
//                    m.setFlag(Flags.Flag.SEEN, true);//标记成已读
                    mail.setReadFlag(0);//已读
            sql += "select count(*) from t482101H ";
            sql += " where userCode=" + GridUtils.prossSqlParm(userCode);
            if (mailType < 3) {
                sql += " and mailType=" + mailType;//0:草稿箱 1:收件箱 2:发件箱
            }
            if (StringUtils.isNotBlank(email)) {
                if (mailType == 1) {
                    sql += " and receiver like '%" + email + "%'";
                } else if (mailType == 2) {
                    sql += " and sender =" + GridUtils.prossSqlParm(email);
                } else if (mailType == 3) {
                    sql += " and isnull(handle_time,'') <> '' and isnull(handle_time,'') < getdate() ";
                }
                if (m.isExpunged()) {//检查一个消息是否已被删除。‌
                    mail.setDeleteFlag(1);//已删除
                } else {
                    mail.setDeleteFlag(0);//已删除
                }
                mail.setMailType(1);//收件
                mail.setClassType(1);
                mail.setUserCode((String) session.getAttribute(SessionKey.USERCODE));
                mail.setUserName((String) session.getAttribute(SessionKey.USERNAME));
                mail.setCompanyId((String) session.getAttribute(SessionKey.COMPANY_ID));
                mail.setCompanyName((String) session.getAttribute(SessionKey.COMPANY_NAME));
                mail.setSubject(m.getSubject());//标题
                String result = "";
                if (m.isMimeType("text/plain")) {
                    result = m.getContent().toString();
                }else if (m.isMimeType("text/html")) {//html格式
                    result = m.getContent().toString();
                }else if (m.isMimeType("multipart/*")) {
                    List<String> fileSeq = new ArrayList<>();
                    MimeMultipart mimeMultipart = (MimeMultipart) m.getContent();
                    String uuId = UUID.randomUUID().toString().toUpperCase();//生成uuid
                    result = getTextFromMimeMultipart(mimeMultipart, uuId, fileSeq);
                    if (fileSeq.size() > 0) {//有附件内容保存
                        mail.setFileUNID(uuId + ";" + StringUtils.join(fileSeq, ";"));
            }
            if (isNoRead) {//0表示未读,1表示已读
                sql += " and isnull(read_flag,0) = 0";
            }
            if (StringUtils.isNotBlank(id)) {//文件夹
                String[] type = id.split("_");
                if (type.length == 2) {
                    if (type[0].equals("folder")) {
                        sql += " and folder_id=" + type[1];
                    } else if (type[0].equals("tag")) {
                        sql += " and tag_list like '%," + type[1] + ",%'";
                    }
                }else {
                    result = m.getContent().toString();
                }
                mail.setContent(result);//保存内容
                mail.setSender(internetAddress.getAddress());//发件人
                from = MimeUtility.decodeText(m.getRecipients(Message.RecipientType.TO)[0].toString());
                internetAddress = new InternetAddress(from);
                mail.setReceiver(internetAddress.getAddress());//收件人
                String cc = "";//抄送人
                Address[] ccAddress = m.getRecipients(Message.RecipientType.CC);
                if (ccAddress != null && ccAddress.length > 0) {
                    for (Address c : ccAddress) {
                        from = MimeUtility.decodeText(c.toString());
                        internetAddress = new InternetAddress(from);
                        cc += internetAddress.getAddress() + ";";
                    }
                    cc = cc.substring(0, cc.lastIndexOf(";"));
                }
                mail.setCc(cc);//抄送人
                String bcc = "";//抄送人
                Address[] bccAddress = m.getRecipients(Message.RecipientType.BCC);
                if (bccAddress != null && bccAddress.length > 0) {
                    for (Address c : bccAddress) {
                        from = MimeUtility.decodeText(c.toString());
                        internetAddress = new InternetAddress(from);
                        bcc += internetAddress.getAddress() + ";";
                    }
                    bcc = bcc.substring(0, bcc.lastIndexOf(";"));
                }
                mail.setBcc(bcc);//密送人
                t482101HEntityList.add(mail);
            }
            return t482101HEntityList;
            return jdbcTemplate.queryForObject(sql, Integer.class);
        } catch (Exception e) {
            throw e;
        }
    }
    // 辅助方法,用于递归获取纯文本邮件内容
    private String getTextFromMimeMultipart(MimeMultipart mimeMultipart, String uuId, List<String> fileSeq) throws Exception {
        int count = mimeMultipart.getCount();
        if (count == 0) {
            throw new MessagingException("Multipart with no body parts");
        }
        boolean multipartAlternative = isMultipartAlternative(mimeMultipart);
        StringBuilder result = new StringBuilder();
        if (multipartAlternative) {
            for (int i = 0; i < count; i++) {
                BodyPart bodyPart = mimeMultipart.getBodyPart(i);
                if (bodyPart.isMimeType("text/plain")) {
                    result.append(bodyPart.getContent());
                    break; // 只获取第一个纯文本内容
                }
            }
        } else {
            for (int i = 0; i < count; i++) {
                BodyPart bodyPart = mimeMultipart.getBodyPart(i);
                if (bodyPart.isMimeType("text/plain")) {
                    result.append(bodyPart.getContent());
                } else if (bodyPart.isMimeType("image/*")) {//图片
                    result.append(saveFileAndImage(bodyPart, "image", uuId));
                } else if (Part.ATTACHMENT.equalsIgnoreCase(bodyPart.getDisposition())) {//附件
                    fileSeq.add(saveFileAndImage(bodyPart, Part.ATTACHMENT, uuId));
                } else if (bodyPart.isMimeType("multipart/*")) {
                    result.append(getTextFromMimeMultipart((MimeMultipart) bodyPart.getContent(), uuId, fileSeq));
                }
            }
        }
        return result.toString();
    }
    // 辅助方法,判断是否为multipart/alternative类型的邮件
    private boolean isMultipartAlternative(MimeMultipart mimeMultipart) throws Exception {
        boolean textPlainFound = false;
        boolean textHtmlFound = false;
        int count = mimeMultipart.getCount();
        for (int i = 0; i < count; i++) {
            BodyPart bodyPart = mimeMultipart.getBodyPart(i);
            if (bodyPart.isMimeType("text/plain")) {
                textPlainFound = true;
            } else if (bodyPart.isMimeType("text/html")) {
                textHtmlFound = true;
            }
        }
        return textPlainFound && textHtmlFound;
    }
    private String saveFileAndImage(BodyPart bodyPart, String type, String unId) throws Exception {
        try {
            String fileName = MimeUtility.decodeText(bodyPart.getFileName());
            if (type.equals("image")) {
                String pattern = ".*\\.(jpg|jpeg|png|gif)$";
                fileName = Pattern.matches(pattern, fileName) ? fileName : fileName + ".jpg";
            }
            File file = new File(fileName);
            FileUtils.copyInputStreamToFile(bodyPart.getInputStream(), file);
            AttachmentEntity attachmentEntity = new AttachmentEntity();
            attachmentEntity.setDoccode("");
            attachmentEntity.setRowId("");
            attachmentEntity.setFormId(482101);
            attachmentEntity.setUnid(unId);
            attachmentEntity.setSeq(null);
            attachmentEntity.setFieldId("file");
            attachmentEntity.setPhysicalFile(file.getName());
            attachmentEntity.setOriginalFileName(file.getName());
            AttachmentIfc attachmentIfc = (AttachmentIfc) FactoryBean.getBean("AttachmentImpl");
            //保存附件
            AttachmentWhereEntity attachmentWhereEntity = attachmentIfc.saveAttachment(attachmentEntity, file, "2");
            if (type.equals("image")) {
                //输出 url
//                return imgData.getImageUrl(attachmentWhereEntity.getUnid() + ";" + attachmentWhereEntity.getSeq(), null,
//                        null, true, true, null);
                return shoppingImageServer + "/uploads/attachment/" + 82 + "/482101/" + attachmentWhereEntity.getUnid() + "@p@" + attachmentWhereEntity.getSeq() + ".jpg";
            } else if (type.equals(Part.ATTACHMENT)) {
                return attachmentWhereEntity.getSeq() + "";
            } else {
                return null;
            }
        } catch (Exception e) {
            throw e;
            return 0;
        }
    }
}