package com.guwan.util;

import com.guwan.common.R;
import com.guwan.config.GlobalValue;
import com.guwan.config.MinioConfig;
import io.minio.MinioClient;
import io.minio.PutObjectOptions;
import org.apache.commons.io.FilenameUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.UUID;

@Component
public class UploadUtil {
    private static MinioClient minioClient;

    private static MinioConfig minioConfig;

    public UploadUtil(MinioClient minioClient,
                      MinioConfig minioConfig) {
        UploadUtil.minioClient = minioClient;
        UploadUtil.minioConfig = minioConfig;
    }

    public static String gbUpload(MultipartFile file) {
        if (file.isEmpty() || file.getSize() == 0) {
            System.out.println("文件不能为空");
        }
        String fileName = null;

        String catalogue;

        try {
            String extension = FilenameUtils.getExtension(file.getOriginalFilename()); //后缀名
            if (extension.equals("png") || extension.equals("jpg")){
                catalogue = "photo/";
            }else if (extension.equals("mp4")){
                catalogue = "video/";
            }else {
                catalogue = "files/";
            }

            fileName = catalogue + "t_" +
                    UUID.randomUUID().toString().replace("-","") +
                    "." + extension;
            InputStream inputStream = file.getInputStream();
            PutObjectOptions putObjectOptions = new PutObjectOptions(inputStream.available(), -1);
            putObjectOptions.setContentType(file.getContentType());
            minioClient.putObject(
                    minioConfig.getBucketName(), fileName, inputStream, putObjectOptions);
            inputStream.close();
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        System.out.println("方法结束");

        return minioConfig.getMinioEndpoint() + "/" +
                minioConfig.getBucketName() + "/" + fileName;
    }


}
