package com.energy.manage.service.util;


import io.minio.GetObjectArgs;
import io.minio.ListObjectsArgs;
import io.minio.MinioClient;
import io.minio.Result;
import io.minio.messages.Item;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.InputStream;

/**
 * 批量下载minio文件
 */
@Slf4j
@Component
public class BatchDownloadUtil {


    @Autowired
    private MinioClient minioClient;

    @Value("${file.download.dir:/usr/local/Downloads/zn/minio-data/}")
    public String localDir;

    /**
     * 下载minio中一个桶下de资源
     * @param bucketName 风场编号
     * @param resoucePath 桶下资源路径（批次编号/）
     * @return
     */
    public String backResourceAddress(String bucketName,String resoucePath){
        ListObjectsArgs listObjectsArgs = ListObjectsArgs.builder().bucket(bucketName).prefix(resoucePath).build();
        try {
            return findAndSaveFile(listObjectsArgs,bucketName );
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private String findAndSaveFile(ListObjectsArgs listObjectsArgs,String bucketName) throws Exception {

        File ifile = new File(localDir + bucketName);
        ifile.mkdirs();

        Iterable<Result<Item>> results = minioClient.listObjects(listObjectsArgs);
        if(results == null){
            ifile.delete();
            return null;
        }
        int count = 0;
        for (Result<Item> result : results) {
            Item item = result.get();
            if (item.isDir()) {
                ListObjectsArgs args = ListObjectsArgs.builder().bucket(bucketName).prefix(item.objectName()).build();
                findAndSaveFile(args,bucketName);
            } else {
                GetObjectArgs getObjectArgs = GetObjectArgs.builder().bucket(bucketName).object(item.objectName()).build();
                String objectName = item.objectName();
                // Create a local file with the same name as the object
                File file = new File(localDir +File.separator + bucketName+ File.separator + objectName);
                // Create parent directories if needed
                file.getParentFile().mkdirs();
                log.info("下载文件个数count = {}",++count);
                // Get the object as an input stream
                InputStream stream = minioClient.getObject(getObjectArgs);
                    // Copy the input stream to the file
                FileUtils.copyInputStreamToFile(stream, file);
                log.info("文件：{} 下载成功！", item.objectName());
            }
        }

        return ifile.getPath();
    }


}
