package com.quanxiaoha.cms.service.impl;

import com.quanxiaoha.cms.common.EditorMdUploadImageResponse;
import com.quanxiaoha.cms.exception.BaseException;
import com.quanxiaoha.cms.model.vo.UploadImageFormVO;
import com.quanxiaoha.cms.service.FileService;
import com.quanxiaoha.cms.utils.KeyUtil;
import com.quanxiaoha.cms.utils.MinioOSSHelper;
import lombok.extern.slf4j.Slf4j;
import net.coobird.thumbnailator.Thumbnails;
import org.apache.commons.lang3.StringUtils;
import org.apache.tomcat.util.http.fileupload.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * @author: 犬小哈
 * @date: 2021/4/14
 * @time: 4:48 下午
 * @version: 1.0.0
 * @description:
 **/
@Service
@Slf4j
public class FileServiceImpl implements FileService {

    @Autowired
    private MinioOSSHelper minioOSSHelper;
    @Value("${minio.endpoint}")
    private String endpoint;
    @Value("${minio.bucketName}")
    private String bucketName;

    @Override
    public EditorMdUploadImageResponse uploadFile(MultipartFile file, UploadImageFormVO uploadImageFormVO) {
        log.info("file upload start ==>");
        if (file == null) {
            log.warn("file upload error: the file is null.");
            throw new BaseException("上传文件为空");
        }
        log.info("file info ==> contentType:{}, originName:{}", file.getContentType(), file.getOriginalFilename());

        String objectName = KeyUtil.genUniqueKey();

        String tmpDir = System.getProperty("java.io.tmpdir");
        String filePath = tmpDir + objectName;
        String compressedFilePath = null;
        try {
            file.transferTo(new File(filePath));

            boolean isSuccess = false;
            // 图片是否需要压缩
            boolean isCompress = uploadImageFormVO.getIsCompress();
            if (isCompress) {
                Float quality = uploadImageFormVO.getQuality();
                compressedFilePath = filePath + "-compressed.jpg";
                Thumbnails.of(new File(filePath))
                        .scale(1.0f)
                        .outputQuality(quality == null ? 0.6f : quality)
                        .toFile(new File(compressedFilePath));

                long objectSize = new File(compressedFilePath).length();
                String contentType = file.getContentType();
                isSuccess = minioOSSHelper.uploadFile(objectName, compressedFilePath, objectSize, contentType);
            } else {
                long objectSize = file.getSize();
                String contentType = file.getContentType();
                isSuccess = minioOSSHelper.uploadFile(objectName, filePath, objectSize, contentType);
            }

            if (isSuccess) {
                String url = String.format("%s/%s/%s", endpoint, bucketName, objectName);
                log.info("url: {}", url);
                return new EditorMdUploadImageResponse().success(url);
            }
        } catch (Exception e) {
            log.error("上传文件异常:", e);
        } finally {
            try {
                FileUtils.forceDelete(new File(filePath));
                if (StringUtils.isNotBlank(compressedFilePath)) {
                    FileUtils.forceDelete(new File(compressedFilePath));
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return new EditorMdUploadImageResponse().fail("上传文件失败");
    }
}