package com.dcsoft.file.controller;

import io.minio.BucketExistsArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.RemoveObjectArgs;
import lombok.Data;
import org.springframework.web.multipart.MultipartFile;

import java.text.SimpleDateFormat;
import java.util.Date;

@Data
public class MinIO {

    private String address; //IP地址
    private String userName; //用户名
    private String password; //密码
    private MinioClient minioClient;  //操作对象
    MinIO(String address, String userName, String password) {
        this.address = address;
        this.userName = userName;
        this.password = password;
    }
    //获取操作对象：
    public MinioClient getMinioClient() {
        if (this.minioClient == null) {
            this.minioClient = MinioClient.builder()
                    .endpoint(this.getAddress())
                    .credentials(this.getUserName(), this.getPassword())
                    .build();
        }
        return this.minioClient;
    }
    //上传文件：
    public String upload(MultipartFile multipartFile, String bucketName) throws Exception {
        //一、设置文件存放的路径信息
        String fileName = multipartFile.getName();        //获取文件名称：
        String timeRandom = String.valueOf(System.currentTimeMillis());        //获取当前时间戳：
        fileName = timeRandom + "_" + fileName;         //拼接文件名：
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");  //格式化当前日期：
        String objectName = sdf.format(new Date()) + "/" + fileName;       //最后存储的路径：  格式为：时间/文件
        //二、上传文件
        this.getMinioClient().putObject(PutObjectArgs.builder().
                bucket(bucketName) //桶名称
                .object(objectName) //路径
                //以下为默认配置：
                .stream(multipartFile.getInputStream(), multipartFile.getSize(), -1)
                .contentType(multipartFile.getContentType())
                .build());
        //三、访问路径：
        return this.address + "/" + bucketName + "/" + objectName;
    }
    //删除文件：
    public   void delete(String bucketName,String fileName) {
        /**
         * String bucketName = "test2";
         * String fileName = "/2023-04-07/16808560218465670_img.png";
         * address+bucketName+fileName 就是访问路径，删除需要后两个参数。
         */
        try {
            this.getMinioClient().removeObject(RemoveObjectArgs.builder().bucket(bucketName).object(fileName).build());
        } catch (Exception e) {
            System.out.println("删除失败");
        }
        System.out.println("删除成功");
    }
    //查询某个桶是否存在：
    public Boolean isExit(String bucketName) throws Exception {
        boolean found =
                this.getMinioClient().bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
        if (found) {
            System.out.println("存储桶存在！");
            return true;
        } else {
            System.out.println("存储桶不存在！");
            return false;
        }
    }

}
