package com.staffing.common.utils;

import com.github.pagehelper.util.StringUtil;
import io.minio.*;
import io.minio.errors.*;
import io.minio.http.Method;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.concurrent.TimeUnit;


@Component
public class MinioUtil {
    private Logger logger = LoggerFactory.getLogger(MinioUtil.class);

    @Autowired
    private MinioClient minioClient;

    /**
     * 创建bucket
     * */
    private void createBucket(String bucketName) throws Exception {
        BucketExistsArgs existsArgs = BucketExistsArgs.builder().bucket(bucketName).build();
        if(!minioClient.bucketExists(existsArgs)) {
            MakeBucketArgs makeArgs = MakeBucketArgs.builder().bucket(bucketName).build();
            minioClient.makeBucket(makeArgs);
            logger.info("bucket {} 不存在， 自动创建该bucket", bucketName);
        }
    }

    /**
     * 从给定输入流中传输对象并放入bucket
     * */
    public ObjectWriteResponse putObject(String bucketName, String objectName, InputStream stream, long objectSize, String contentType) throws Exception {
        if (StringUtils.isEmpty(bucketName)) {
            throw new RuntimeException("保存的bucketName为空");
        }
        createBucket(bucketName);
        //long objSize = -1;
        long partSize = -1; //objectSize已知，partSize设为-1意为自动设置
        PutObjectArgs putArgs = PutObjectArgs.builder()
                .bucket(bucketName)
                .object(objectName)
                .stream(stream, objectSize, partSize)
                .contentType(contentType)
                .build();
        ObjectWriteResponse response = minioClient.putObject(putArgs);

        return response;
    }
    public enum ViewContentType {
        DEFAULT("default","application/octet-stream"),
        JPG("jpg", "image/jpeg"),
        TIFF("tiff", "image/tiff"),
        GIF("gif", "image/gif"),
        JFIF("jfif", "image/jpeg"),
        PNG("png", "image/png"),
        TIF("tif", "image/tiff"),
        ICO("ico", "image/x-icon"),
        JPEG("jpeg", "image/jpeg"),
        WBMP("wbmp", "image/vnd.wap.wbmp"),
        FAX("fax", "image/fax"),
        NET("net", "image/pnetvue"),
        JPE("jpe", "image/jpeg"),
        RP("rp", "image/vnd.rn-realpix");

        private String prefix;

        private String type;

        public static String getContentType(String prefix){
            if(StringUtil.isEmpty(prefix)){
                return DEFAULT.getType();
            }
            prefix = prefix.substring(prefix.lastIndexOf(".") + 1);
            for (ViewContentType value : ViewContentType.values()) {
                if(prefix.equalsIgnoreCase(value.getPrefix())){
                    return value.getType();
                }
            }
            return DEFAULT.getType();
        }

        ViewContentType(String prefix, String type) {
            this.prefix = prefix;
            this.type = type;
        }

        public String getPrefix() {
            return prefix;
        }

        public String getType() {
            return type;
        }
    }
    /**
     * 从bucket获取指定对象的输入流，后续可使用输入流读取对象
     * getObject与minio server连接默认保持5分钟，
     * 每隔15s由minio server向客户端发送keep-alive check，5分钟后由客户端主动发起关闭连接
     * */
    public InputStream getObject(String bucketName, String objectName) throws Exception{
        GetObjectArgs args = GetObjectArgs.builder()
                .bucket(bucketName)
                .object(objectName)
                .build();
        return minioClient.getObject(args);
    }

    /**
     * 获取对象的临时访问url，有效期5分钟
     * */
    public String getObjectURL(String bucketName, String objectName){
        GetPresignedObjectUrlArgs args = GetPresignedObjectUrlArgs.builder()
                .bucket(bucketName)
                .object(objectName)
                .expiry(5, TimeUnit.MINUTES)
                .method(Method.GET)
                .build();
        try {
            return minioClient.getPresignedObjectUrl(args);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 删除对象
     * */
    public void removeObject(String bucketName, String objectName) throws Exception {
        RemoveObjectArgs args = RemoveObjectArgs.builder()
                .bucket(bucketName)
                .object(objectName)
                .build();
        minioClient.removeObject(args);
        logger.info("bucket:{}文件{}已删除", bucketName , objectName);
    }

    /**
     * 上传MultipartFile
     * @param bucketName 文件存放的bucket
     * @param filePath 文件在bucket里的全目录
     * */
    public ObjectWriteResponse uploadFile(String bucketName, String filePath, MultipartFile file) throws Exception{
        return putObject(bucketName, filePath, file.getInputStream(), file.getSize(), file.getContentType());
    }

    /**
     * 从minio下载文件，直接通过response传输
     * */
    public void downloadFile(String bucketName, String filePath, HttpServletResponse response) throws Exception {

        try (InputStream is = getObject(bucketName, filePath);
             BufferedInputStream bis = new BufferedInputStream(is);
             OutputStream os = response.getOutputStream()) {
            //try {
			/*InputStream is = getObject(bucketName, filePath);
			BufferedInputStream bis = new BufferedInputStream(is);
			OutputStream os = response.getOutputStream();*/
            response.setContentType("application/force-download;charset=utf-8");// 设置强制下载而不是直接打开
            response.addHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(filePath, "UTF-8"));// 设置文件名


            byte[] buffer = new byte[1024*1024*1024]; //buffer 1M
            int offset = bis.read(buffer);
            while (offset != -1) {
                os.write(buffer, 0, offset);
                offset = bis.read(buffer);
            }
            os.flush();
        } catch (Exception e) {
            logger.error("下载文件失败"+e.getMessage(), e);
            throw new RuntimeException("下载文件失败" , e);
        }
    }
}