package com.nbport.zgwl.controller;

import com.nbport.zgwl.common.R;
import com.nbport.zgwl.exception.ServiceException;
import com.nbport.zgwl.service.LocalFileService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import java.util.Map;

@RestController
@RequestMapping("/trans/minio/file")
@Slf4j
@RequiredArgsConstructor
@Validated
public class MinioFileController {

    private final LocalFileService localFileService;

    @PostMapping(value = "/uploadOutie", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public R<String> uploadOutie(MultipartHttpServletRequest request) {
        Map<String, MultipartFile> fileMap = request.getFileMap();
        if (CollectionUtils.isEmpty(fileMap)) {
            throw new ServiceException("请上传文件");
        }
        MultipartFile file = fileMap.values().iterator().next();
        log.info("接收到上传文件请求，fileName={}", file.getOriginalFilename());
        String relativePath = localFileService.upload(file);
        return R.data(relativePath);
    }

    @GetMapping("/download")
    public ResponseEntity<ByteArrayResource> download(@RequestParam("fileName") String fileName) {
        log.info("接收到文件下载请求，fileName={}", fileName);
        return localFileService.download(fileName);
    }
}
