package org.springblade.utils;

import cn.hutool.core.io.IoUtil;
import lombok.SneakyThrows;
import org.springblade.core.oss.MinioTemplate;
import org.springblade.core.oss.model.BladeFile;
import org.springblade.core.tool.api.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.Base64Utils;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;

@Component
public class OssUtil {

	@Autowired
	private MinioTemplate minioTemplate;
	@Value("${oss.endpoint}")
	private String endpoint;
	@Value("${oss.access-key}")
	private String accessKey;
	@Value("${oss.secret-key}")
	private String secretKey;
	@Value("${oss.return-path}")
	private String returnPath;
	@Value("${oss.bucket-name}")
	private String bucketName;


	/**
	 * @param file
	 * @return
	 */
	@SneakyThrows
	public R<BladeFile> uploadFile(MultipartFile file){


//		String fileName = "upload/" + DateUtil.today() + "/" + StringUtil.randomUUID() + "." + FileUtil.getFileExtension(file.getOriginalFilename());
		try {
			BladeFile bladeFile = minioTemplate.putFile(bucketName, file.getOriginalFilename(), file.getInputStream());
//			// 使用MinIO服务的URL，端口，Access key和Secret key创建一个MinioClient对象
//			MinioClient minioClient = MinioClient.builder().endpoint(endpoint).credentials(accessKey, secretKey).build();
//			// 检查存储桶是否已经存在
//			boolean isExist = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
//			if(isExist) {
//				System.out.println(bucketName+" already exists.");
//			} else {
//				minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
//			}
//			// 使用putObject上传一个文件到存储桶中。
//			minioClient.putObject(PutObjectArgs.builder()
//					.contentType("application/octet-stream")
//					.bucket(bucketName)
//					.stream(file.getInputStream(), file.getInputStream().available(), -1)
//					.object(fileName)
//					.build());
//
//			BladeFile bladeFile = new BladeFile();
//			bladeFile.setLink((returnPath + fileName).trim());
//			bladeFile.setDomain(endpoint);
//			bladeFile.setOriginalName(file.getOriginalFilename());
//			bladeFile.setName(fileName);
			return R.data(bladeFile);
		} catch(Exception e) {
			e.printStackTrace();
			return R.fail(e.getMessage());
		}
	}

	public String getImagesBase64(InputStream inputStream){
		byte[] imageBytes = IoUtil.readBytes(inputStream);
		return Base64Utils.encodeToString(imageBytes);
	}
}
