package com.railway.system.service.impl;

import com.railway.common.utils.file.FileUploadUtils;
import com.railway.system.domain.MinioConfig;
import com.railway.system.service.ISysFileService;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

/**
 * Minio 文件存储
 *
 * @author railway
 */
@Service
public class MinioSysFileServiceImpl extends AbstractFileService implements ISysFileService {

  private final MinioConfig minioConfig;
  private final MinioClient client;

  public MinioSysFileServiceImpl(MinioConfig minioConfig, MinioClient client) {
    this.minioConfig = minioConfig;
    this.client = client;
  }

  /**
   * 本地文件上传接口
   *
   * @param file 上传的文件
   * @return 访问地址
   * @throws Exception 文件上传异常
   */
  @Override
  public String uploadFile(MultipartFile file) throws Exception {
    String fileName = FileUploadUtils.extractFilename(file);
    PutObjectArgs args = PutObjectArgs.builder()
        .bucket(minioConfig.getBucketName())
        .object(fileName)
        .stream(file.getInputStream(), file.getSize(), -1)
        .contentType(file.getContentType())
        .build();
    client.putObject(args);
    return minioConfig.getUrl() + "/" + minioConfig.getBucketName() + "/" + fileName;
  }
}
