package com.yx.face.boot.uitls;


import io.minio.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;

/**
 * @ProjectName: fyzd-phone
 * @Package: com.yx.face.boot.uitls
 * @ClassName: MiniOUtils
 * @Author: 崔哥
 * @Description:
 * @Date: 2021/11/24 11:27
 * @Version: 1.0
 */
@Component
public class MiniOUtils {

    //    @Value("${web.address}")
    private static final String ip = "https://ldb-airport.hz-hanghui.com:9100/img/";

//    /**
//     * ACCESS_KEY
//     */
//    private static String MINIO_ACCESS_KEY = "admin";
//
//    /**
//     * 服务器路径
//     */
//    private static String MINIO_PATH_URL = "127.0.0.1:9000";
//
//    /**
//     * 文件存储块
//     */
//    private static String MINIO_OSS_BUCKET = "hanghui";
//
//    /**
//     * SECRET_KEY
//     */
//    private static String MINIO_SECRET_KEY = "nqj##3961";
//
//    /**
//     * REGION
//     */
//    private static String MINIO_REGION;


    private static String minioUrl;
    private static String minioName;
    private static String minioPass;
    private static String bucketName;

    public static void setMinioUrl(String minioUrl) {
        MiniOUtils.minioUrl = minioUrl;
    }

    public static void setMinioName(String minioName) {
        MiniOUtils.minioName = minioName;
    }

    public static void setMinioPass(String minioPass) {
        MiniOUtils.minioPass = minioPass;
    }

    public static void setBucketName(String bucketName) {
        MiniOUtils.bucketName = bucketName;
    }

    public static String getMinioUrl() {
        return minioUrl;
    }

    public static String getBucketName() {
        return bucketName;
    }


    /**
     * 构建连接客户端
     */
    public static MinioClient minioClient = null;


    /**
     * 创建桶
     *
     * @param bucket 桶
     */
    public static void makeBucket(String bucket) throws Exception {
        initMinio(minioUrl, minioName, minioPass);
        // 判断桶是否存在
        boolean isExist = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucket).build());
        if (!isExist) {
            // 新建桶
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucket).build());
        }
    }


    /**
     * 通过二进制流上传到MiniO存储
     *
     * @param inputStream 文件
     * @param fileName    文件名
     * @return
     */
    public static String fileUpload2MiniO(InputStream inputStream, String fileName) {
        initMinio(minioUrl, minioName, minioPass);
        try {
            boolean exists = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
            if (!exists) {
                //不存在就创建一个新的BUCKET
                makeBucket(bucketName);
            }
            String contentType = getcontentType(fileName);
            minioClient.putObject(PutObjectArgs.builder().bucket(bucketName)
                    .object(fileName)
                    .stream(inputStream, Long.valueOf(inputStream.available()), -1l)
                    .contentType(contentType).build());
        } catch (Exception e) {
            new RuntimeException("上传发生错误!");
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return ip + bucketName + "/" + fileName;
    }

    /**
     * 文件下载
     *
     * @param fileName 文件名
     * @return InputStream
     */
    public static InputStream downLoadFile(String fileName) {
        initMinio(minioUrl, minioName, minioPass);
        InputStream inputStream = null;
        try {
            StatObjectResponse statObjectResponse = minioClient.statObject(StatObjectArgs.builder().bucket(bucketName).object(fileName).build());
            if (statObjectResponse.size() > 0) {
                inputStream = minioClient.getObject(GetObjectArgs.builder().bucket(bucketName).object(fileName).build());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return inputStream;
    }

    /**
     * 删除文件
     *
     * @param fileName
     * @return flag
     */
    public static Boolean removeFile(String fileName) {
        initMinio(minioUrl, minioName, minioPass);
        boolean flag = false;
        try {
            minioClient.removeObject(RemoveObjectArgs.builder().bucket(bucketName).object(fileName).build());
            flag = true;
        } catch (Exception e) {
            e.printStackTrace();
            flag = false;
        }
        return flag;
    }


    /**
     * 删除桶（只有当桶中没有数据的时候才能删除）
     *
     * @param bucketName
     * @return
     */
    public static boolean removeBucket(String bucketName) {
        initMinio(minioUrl, minioName, minioPass);
        boolean exists = false;
        try {
            exists = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
            if (exists) {
                minioClient.removeBucket(RemoveBucketArgs.builder().bucket(bucketName).build());
                exists = true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return exists;
    }

    /**
     * 获取日期
     *
     * @return 例: 20210506
     */
    public static String getToDay() {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyddMM");
        return formatter.format(System.currentTimeMillis());
    }

    /**
     * 判断文件名是否带盘符，重新处理
     *
     * @param fileName
     * @return
     */
    public static String getFileName(String fileName) {
        //判断是否带有盘符信息
        // Check for Unix-style path
        int unixSep = fileName.lastIndexOf('/');
        // Check for Windows-style path
        int winSep = fileName.lastIndexOf('\\');
        // Cut off at latest possible point
        int pos = (winSep > unixSep ? winSep : unixSep);
        if (pos != -1) {
            // Any sort of path separator found...
            fileName = fileName.substring(pos + 1);
        }
        //替换上传文件名字的特殊字符
        fileName = fileName.replace("=", "").replace(",", "").replace("&", "").replace("#", "");
        return fileName;
    }

    /**
     * Description: 判断OSS服务文件上传时文件的contentType
     *
     * @param FilenameExtension 文件后缀
     * @return String
     */
    public static String getcontentType(String FilenameExtension) {
        if ("bmp".equalsIgnoreCase(FilenameExtension)) {
            return "image/bmp";
        }
        if ("gif".equalsIgnoreCase(FilenameExtension)) {
            return "image/gif";
        }
        if ("jpeg".equalsIgnoreCase(FilenameExtension) ||
                "jpg".equalsIgnoreCase(FilenameExtension) ||
                "png".equalsIgnoreCase(FilenameExtension)) {
            return "image/jpeg";
        }
        if ("html".equalsIgnoreCase(FilenameExtension)) {
            return "text/html";
        }
        if ("txt".equalsIgnoreCase(FilenameExtension)) {
            return "text/plain";
        }
        if ("vsd".equalsIgnoreCase(FilenameExtension)) {
            return "application/vnd.visio";
        }
        if ("pptx".equalsIgnoreCase(FilenameExtension) ||
                "ppt".equalsIgnoreCase(FilenameExtension)) {
            return "application/vnd.ms-powerpoint";
        }
        if ("docx".equalsIgnoreCase(FilenameExtension) ||
                "doc".equalsIgnoreCase(FilenameExtension)) {
            return "application/msword";
        }
        if ("xml".equalsIgnoreCase(FilenameExtension)) {
            return "text/xml";
        }
        return "image/jpeg";
    }

    /**
     * 初始化客户端
     *
     * @param minioUrl
     * @param minioName
     * @param minioPass
     * @return
     */
    private static MinioClient initMinio(String minioUrl, String minioName, String minioPass) {
        if (minioClient == null) {
            minioClient = MinioClient.builder().endpoint(minioUrl).credentials(minioName, minioPass).build();
        }
        return minioClient;
    }
}
