package com.friday.custody.utils;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.fastjson.JSON;
import com.friday.custody.entity.CustodyPullMailFailureLogEntity;
import com.friday.custody.entity.TenantEmailAuthorizationInfoEntity;
import com.friday.custody.service.basicService.impl.CustodyPullMailFailureLogServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.mail.*;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

/**
 * @Description
 * @Author k0051745
 * @Date: 2022/11/15
 */
@Component
@Slf4j
public class MailNewUtils {

    @Value("file.parentPath.realPath")
    public String REALPATH;

    public String getDefaultAttachmentParentPath(TenantEmailAuthorizationInfoEntity tenantEmailAuthorizationInfo){
        log.info("getDefaultAttachmentParentPath 入参：{}", JSON.toJSONString(tenantEmailAuthorizationInfo));
        String retureStr = "";
        String osName = System.getProperty("os.name");
        log.info("getDefaultAttachmentParentPath 操作系统名字为{}",osName);
        if (osName.toLowerCase().indexOf("win") != -1) {
            retureStr = "C:\\temp\\";
        }else{
            retureStr = REALPATH;
        }
        // /app/work/P1002894/34/all/
        retureStr = retureStr + tenantEmailAuthorizationInfo.getTenantName() + File.separator
                + tenantEmailAuthorizationInfo.getTrustNo() + File.separator
                + (StringUtils.isBlank(tenantEmailAuthorizationInfo.getPurpose())?"default":tenantEmailAuthorizationInfo.getPurpose()) + File.separator;

        log.info("getDefaultAttachmentParentPath 返回：{}",retureStr);
        return retureStr;
    }

    // 打印最新的 【number】个邮件的相关信息
    public void printMessageInfo(Message[] weMessage,int number){
        if(weMessage == null || weMessage.length < 1){
            log.error("printMessageInfo 邮件数组为空！");
            return;
        }
        List<Message> messages = new ArrayList<>(weMessage.length);
        for (int i = 0; i < weMessage.length; i++) {
            messages.add(weMessage[i]);
        }

        //邮件从最近到从前
        Collections.reverse(messages);

        for (int j = 0; j < number; j++) {
            if(j > weMessage.length - 1){
                break;
            }
            try {
                Message message = messages.get(j);
                MailUtil re;
                re = new MailUtil((MimeMessage) message);
                log.info("邮件主题:" + re.getSubject());
                log.info("邮件是否包含附件:" + re.isContainAttach(message));
                log.info("邮件发送人地址:" + re.getFrom());
                Part part = message;
                if (part.isMimeType("multipart/*")) {
                    Multipart mp = (Multipart) part.getContent();
                    BodyPart mPart;
                    for (int i = 0; i < mp.getCount(); i++) {
                        String fileName = "";
                        mPart = mp.getBodyPart(i);
                        String disposition = mPart.getDisposition();
                        if (Part.ATTACHMENT.equals(disposition) || Part.INLINE.equals(disposition)) {
                            fileName = mPart.getFileName();
                            if (null != fileName && fileName.toLowerCase().indexOf("gb2312") != -1) {
                                fileName = MimeUtility.decodeText(fileName);
                            }
                            fileName = MailUtil.decodeText(fileName);
                        }  else {
                            fileName = mPart.getFileName();
                            if ((fileName != null) && (fileName.toLowerCase().indexOf("GB2312") != -1)) {
                                fileName = MimeUtility.decodeText(fileName);
                                fileName = MailUtil.decodeText(fileName);
                            }
                        }
                        log.info("邮件主题为{},附件名称为{}",re.getSubject(),fileName);
                    }
                } else if (part.isMimeType("message/rfc822")) {
                    log.info("mimeType = {}","message/rfc822");
                }
            } catch (Exception e) {
                log.error("",e);
            }
        }
    }

    public void saveAttachment(Part part,String parentPath){
        try{
            String fileName;
            if (part.isMimeType("multipart/*")) {
                Multipart mp = (Multipart) part.getContent();
                BodyPart mPart;
                for (int i = 0; i < mp.getCount(); i++) {
                    mPart = mp.getBodyPart(i);
                    String disposition = mPart.getDisposition();
                    if (Part.ATTACHMENT.equals(disposition) || Part.INLINE.equals(disposition)) {
                        fileName = mPart.getFileName();
                        if (null != fileName && fileName.toLowerCase().indexOf("gb2312") != -1) {
                            fileName = MimeUtility.decodeText(fileName);
                        }
                        this.saveFile(MailUtil.decodeText(fileName), mPart.getInputStream(),parentPath);
                    } else if (mPart.isMimeType("multipart/*")) {
                        this.saveAttachMent(mPart,parentPath);
                    } else {
                        fileName = mPart.getFileName();
                        if ((fileName != null) && (fileName.toLowerCase().indexOf("GB2312") != -1)) {
                            fileName = MimeUtility.decodeText(fileName);
                            this.saveFile(MailUtil.decodeText(fileName), mPart.getInputStream(),parentPath);

                        }
                    }
                }
            } else if (part.isMimeType("message/rfc822")) {
                this.saveAttachMent((Part) part.getContent(),parentPath);
            }
        }catch (Exception e){
            log.error("saveAttachment：{}",e);
        }
    }

    private void saveFile(String fileName, InputStream in,String parentPath) throws IOException {
        String storeDir = parentPath;

        File file = new File(storeDir);
        if(!file.exists()){
            file.mkdirs();
        }

        log.info("storeDir:{},fileName={}",  storeDir,fileName);
        File targetFile = new File(storeDir + File.separator + fileName);
        if(!targetFile.exists()){
            FileOutputStream fos = new FileOutputStream(targetFile);
            IOUtils.copy(in, fos);
            IOUtils.closeQuietly(fos);
            IOUtils.closeQuietly(in);
        }else{
            log.info("saveFile:targetFile:{}已经存在了",targetFile.getAbsolutePath());
        }

    }

    private void saveAttachMent(Part part,String parentPath) throws MessagingException, IOException {
        String fileName;
        if (part.isMimeType("multipart/*")) {
            Multipart mp = (Multipart) part.getContent();
            BodyPart mPart;
            for (int i = 0; i < mp.getCount(); i++) {
                try {
                    mPart = mp.getBodyPart(i);
                    String disposition = mPart.getDisposition();
                    if (Part.ATTACHMENT.equals(disposition) || Part.INLINE.equals(disposition)) {
                        fileName = mPart.getFileName();
                        if (null != fileName && fileName.toLowerCase().indexOf("gb2312") != -1) {
                            fileName = MimeUtility.decodeText(fileName);
                        }
                        this.saveFile(MailUtil.decodeText(fileName), mPart.getInputStream(),parentPath);
                    } else if (mPart.isMimeType("multipart/*")) {
                        this.saveAttachMent(mPart,parentPath);
                    } else {
                        fileName = mPart.getFileName();
                        if ((fileName != null) && (fileName.toLowerCase().indexOf("GB2312") != -1)) {
                            fileName = MimeUtility.decodeText(fileName);
                            this.saveFile(MailUtil.decodeText(fileName), mPart.getInputStream(),parentPath);

                        }
                    }
                } catch (Exception e) {
                    log.error("saveAttachMent发生异常:{}",e);
                }
            }
        } else if (part.isMimeType("message/rfc822")) {
            this.saveAttachMent((Part) part.getContent(),parentPath);
        }
    }
public static void saveMailFailureLog(String admin,String trustNo,String errorMsg){
    CustodyPullMailFailureLogEntity logEntity = new CustodyPullMailFailureLogEntity();
    logEntity.setAdmin(admin);
    logEntity.setTrustNo(trustNo);
    logEntity.setErrorMsg(errorMsg);
    logEntity.setCreateTime(new Date());
    logEntity.setUpdateTime(new Date());
    CustodyPullMailFailureLogServiceImpl logService = new CustodyPullMailFailureLogServiceImpl();

    logService.save(logEntity);
}

}
