package com.casic.missiles.controller;

import cn.hutool.core.lang.Assert;
import com.casic.missiles.dto.ReturnDTO;
import com.casic.missiles.dto.ReturnUtil;
import com.casic.missiles.enums.BusinessExceptionEnum;
import com.casic.missiles.exception.BusinessException;
import com.casic.missiles.utils.MinioUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Objects;

/**
 * @Description:
 * @Author: wangpeng
 * @Date: 2022/11/27 19:38
 */
@Api(tags = "文件上传下载接口")
@Controller
@RequestMapping("/minio/file")
public class MinioFileController {
    @Autowired
    private MinioUtil minioUtil;

    /**
     * 文件上传（minio）
     */
    @ApiOperation("文件上传")
    @PostMapping("/upload")
    @ResponseBody
    public ReturnDTO upload(@RequestBody MultipartFile[] multipartFile) {
        Assert.isFalse(Objects.isNull(multipartFile), () -> {
            throw new BusinessException(BusinessExceptionEnum.UPLOAD_FILE_NULL);
        });
        List<String> nameList = minioUtil.upload(multipartFile);
        return ReturnUtil.success(nameList);
    }

    /**
     * 文件下载（minio）
     */
    @ApiOperation("文件下载")
    @PostMapping("/download/{fileName}")
    @ResponseBody
    public ReturnDTO<ResponseEntity> upload(@PathVariable(name = "fileName") String fileName) {
        ResponseEntity<byte[]> download = minioUtil.download(fileName);
        return ReturnUtil.success(download);
    }

    /**
     * 文件流下载（minio）
     */
    @ApiOperation("文件流下载")
    @PostMapping("/download/stream")
    @ResponseBody
    public void upload(@RequestParam(name = "fileName") String fileName, HttpServletResponse response) {
        minioUtil.downloadStream(fileName, response);
    }

    /**
     * 文件路径（minio）
     * 实现静态文件url获取
     */
    @ApiOperation("文件url获取")
    @GetMapping("/url")
    @ResponseBody
    public ReturnDTO<String> getFileUrl(@RequestParam(name = "fileName") String fileName) {
        return ReturnUtil.success(minioUtil.getFileUrl(fileName));
    }

}
