package org.springblade.utils;

import cn.hutool.core.io.FileTypeUtil;

import io.minio.MinioClient;
import io.swagger.annotations.Api;

import lombok.extern.slf4j.Slf4j;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.DateUtil;
import org.springblade.core.tool.utils.FileUtil;
import org.springblade.core.tool.utils.StringUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;



@RestController
@Slf4j
@RequestMapping("/upload")
@Api(tags = "上传模块")
public class UploadController1 {


	@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;

	private static final String FILE_PNG=".png";
	private static final String FILE_JPG=".jpg";
	private static final String FILE_JPEG=".jpeg";

	@PostMapping("/putfile")
	public R<String> putFile(@RequestParam MultipartFile file){
		String filename = file.getOriginalFilename();
		String fileType = filename.substring(filename.lastIndexOf("."));
		//先判断后缀名
		if (FILE_PNG.equalsIgnoreCase(fileType) || FILE_JPG.equalsIgnoreCase(fileType) || FILE_JPEG.equalsIgnoreCase(fileType)) {
			String type ;
			try {
				type = FileTypeUtil.getType(file.getInputStream());
				//根据首部字节判断文件类型
				if (FILE_PNG.contains(type)||FILE_JPG.contains(type)||FILE_JPEG.contains(type)){
					String fileName = "upload/" + DateUtil.today() + "/" + StringUtil.randomUUID() + "." + FileUtil.getFileExtension(file.getOriginalFilename());
					try {
						// 使用MinIO服务的URL，端口，Access key和Secret key创建一个MinioClient对象
						MinioClient minioClient = new MinioClient(endpoint, accessKey, secretKey);
						// 检查存储桶是否已经存在
						boolean isExist = minioClient.bucketExists(bucketName);
						if(isExist) {
							System.out.println(bucketName+" already exists.");
						} else {

							minioClient.makeBucket(bucketName);
						}
						// 使用putObject上传一个文件到存储桶中。
						minioClient.putObject(bucketName,fileName, file.getInputStream(),file.getInputStream().available(),"application/octet-stream");
					} catch(Exception e) {
						System.out.println("Error occurred: " + e);
						return R.fail("fail");
					}
					return R.data((returnPath+fileName).trim());
				}else{
					return R.fail("不支持的文件格式");
				}
			} catch (Exception e) {
				return R.fail("不支持的文件格式");

			}
		}else{
			return R.fail("不支持的文件格式");
		}
	}




}
