package com.ruoyi.zzb.common.service;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.annotation.DataSource;
import com.ruoyi.common.enums.DataSourceType;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.framework.config.ServerConfig;
import com.ruoyi.zzb.common.domain.BaseFileInfo;
import com.ruoyi.zzb.common.mapper.BaseFileInfoMapper;
import com.ruoyi.zzb.common.utils.CommonUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
@Service
@DataSource(value = DataSourceType.SLAVE)
public class BaseService {

    @Autowired
    private BaseFileInfoMapper baseFileInfoMapper;
    @Autowired
    private ServerConfig serverConfig;
    @Autowired
    private JavaMailSender mailSender;
    @Value("${spring.mail.username}")
    private String from;

    /**
     * 发送一条带附件的邮件消息
     * @param to
     * @param subject
     * @param text
     * @param attachmentPath
     * @throws MessagingException
     */
    public void sendEmail(String to, String subject, String text, String attachmentPath) throws MessagingException {
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        helper.setFrom(from);
        helper.setTo(to);
        helper.setSubject(subject);
        helper.setText(text);
        FileSystemResource file = new FileSystemResource(new File(attachmentPath));
        // 添加附件
        helper.addAttachment(file.getFilename(), file);
        mailSender.send(message);
    }


    /**
     * 根据申请单ID 删除与之关联的文件信息记录
     * @param applyFormId
     * @return
     */
    @Transactional
    public boolean delBaseFileInfosByApplyFormId(String applyFormId){
        int delBaseFileInfoRows = baseFileInfoMapper.deleteById(applyFormId);
        if(delBaseFileInfoRows > 0){
            log.info("当前申请信息关联的文件信息删除成功  申请单ID：{}，删除的数据条数：{}", applyFormId, delBaseFileInfoRows);
            return true;
        } else {
            throw new RuntimeException("数据库申请信息对应的文件信息记录未删除或不存在  申请单ID：" + applyFormId);
        }
    }


    /**
     * 统一处理各模块文件上传，并构造对应数据对象
     * @param files
     * @param moduleCode
     * @param moduleName
     * @param applyFormId
     * @param fileTypeName
     * @param fileTypeCode
     * @param fileStoragePath
     * @return
     * @throws IOException
     */
    public List<BaseFileInfo> doProcessUploadAndBuildParams(MultipartFile[] files, String moduleCode, String moduleName, String applyFormId, String fileTypeName, String fileTypeCode, String fileStoragePath) throws IOException {
        List<BaseFileInfo> rowDataList = new ArrayList<>();
        if(null != files && files.length > 0){
            AtomicInteger fileOrder = new AtomicInteger(0);
            for (MultipartFile file : files) {
                if (!file.isEmpty()) {
                    // 原始文件名
                    String originalFilename = file.getOriginalFilename();
                    // 文件扩展名
                    String fileExtensions = CommonUtils.getFileExtension(originalFilename);
                    // 文件存储ID（MD5值）
                    String fileStorageId = CommonUtils.md5(originalFilename + new Date().getTime());
                    // 上传文件，并返回新的文件名称
                    String newFileName = FileUploadUtils.upload(fileStoragePath, file);
                    log.info("【{}】文件上传成功  申请单ID：{}，文件类型名称：{}，文件名称：{}", moduleName, applyFormId, fileTypeName, originalFilename);
                    // 文件HTTP请求路径
                    String fileRequestPath = serverConfig.getUrl() + newFileName;
                    BaseFileInfo baseFileInfo = new BaseFileInfo();
                    baseFileInfo.setModuleCode(moduleCode);
                    baseFileInfo.setApplyFormId(applyFormId);
                    baseFileInfo.setFileTypeName(fileTypeName);
                    baseFileInfo.setFileTypeCode(fileTypeCode);
                    baseFileInfo.setFileOrder(fileOrder.incrementAndGet());
                    baseFileInfo.setFileOriginalName(originalFilename);
                    baseFileInfo.setFileExtensions(fileExtensions);
                    baseFileInfo.setFileStorageId(fileStorageId);
                    baseFileInfo.setFileRequestPath(fileRequestPath);
                    baseFileInfo.setFileStoragePath(fileStoragePath);
                    baseFileInfo.setIsDelete(0);
                    rowDataList.add(baseFileInfo);
                }
            }
        }
        return rowDataList;
    }

}
