package com.storlead.sales.mail.service.impl;

import cn.hutool.core.util.StrUtil;
import com.storlead.framework.common.util.RandomGenerateHelper;
import com.storlead.sales.mail.entity.MailAttachmentEntity;
import com.storlead.sales.mail.entity.MailTempAttachmentEntity;
import com.storlead.sales.mail.mapper.MailTempAttachmentMapper;
import com.storlead.sales.mail.properties.MailFileProperties;
import com.storlead.sales.mail.service.MailTempAttachmentService;
import com.storlead.framework.mybatis.service.impl.MyBaseServiceImpl;
import com.storlead.sales.mail.util.FileHelper;
import org.apache.commons.io.FilenameUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.mail.BodyPart;
import javax.mail.MessagingException;
import javax.mail.internet.MimeUtility;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * <p>
 * 临时邮件附件表 服务实现类
 * </p>
 *
 * @author chenkq
 * @since 2024-08-09
 */
@Service
public class MailTempAttachmentServiceImpl extends MyBaseServiceImpl<MailTempAttachmentMapper, MailTempAttachmentEntity> implements MailTempAttachmentService {

    @Resource
    private MailFileProperties mailFileProperties;

    @Override
    public MailTempAttachmentEntity saveAttachmentToDatabase(File file, String code,Long mailId) {

        String fileName = StrUtil.isBlank(code) ? file.getName() : file.getName().replace("."+code,"");
        MailTempAttachmentEntity attachment = new MailTempAttachmentEntity();
        attachment.setEmailId(mailId);
        attachment.setFileCode(code);
        attachment.setFileName(FilenameUtils.getBaseName(fileName));
        attachment.setFilePath(file.getAbsolutePath().replace(mailFileProperties.getPath().getPath(),""));
        attachment.setFileExt(FilenameUtils.getExtension(fileName));
        attachment.setFileSize(file.length());
        this.save(attachment);
        return attachment;
    }

    @Override
    public Long saveTempAttachment(MultipartFile file, String downloadDir, Long mailId) {
        try {
            String fileName = file.getOriginalFilename();
            fileName = MimeUtility.decodeText(fileName);
            fileName = fileName.replace("\n", "").replace("\r", "");
            String code =  RandomGenerateHelper.generateRandomString(6);
            // 如果不存在这创建路径
            if (!new File(downloadDir).exists()) {
                new File(downloadDir).mkdirs();
            }
            fileName = fileName+"."+code;
            File filePath = new File(downloadDir +  File.separator + fileName);
            try (FileOutputStream output = new FileOutputStream(filePath)) {
                file.getInputStream().transferTo(output);
            }
            MailTempAttachmentEntity attachment = saveAttachmentToDatabase(filePath,code, mailId);
            return attachment.getId();
        }catch (Exception e) {
            log.error("--upload -- saveTempAttachment --error --",e);
            return null;
        }
    }

    @Override
    public MailTempAttachmentEntity saveTempImageAttachment(MultipartFile file, String downloadDir) {
        try {
            String fileName = file.getOriginalFilename();
            fileName = MimeUtility.decodeText(fileName);
            fileName = fileName.replace("\n", "").replace("\r", "");
            String extension =  FilenameUtils.getExtension(fileName);
            String timestamp = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
            String uniqueId = UUID.randomUUID().toString().replaceAll("-", "").substring(0, 8);

            String newFileName = "image_" + timestamp + "_" + uniqueId + "." + extension;
            // 如果不存在这创建路径
            if (!new File(downloadDir).exists()) {
                new File(downloadDir).mkdirs();
            }
            File filePath = new File(downloadDir +  File.separator + newFileName);
            try (FileOutputStream output = new FileOutputStream(filePath)) {
                file.getInputStream().transferTo(output);
            }
            MailTempAttachmentEntity attachment = saveAttachmentToDatabase(filePath,"", null);
            return attachment;
        }catch (Exception e) {
            log.error("--upload -- saveTempAttachment --error --",e);
            return null;
        }
    }
}
