package com.bonus.mongodb.controller;

import com.bonus.common.core.domain.R;
import com.bonus.mongodb.damain.FileExportVo;
import com.bonus.mongodb.service.MongodbService;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;

@RestController
@RequestMapping("/mongodb/")
@Slf4j
public class MongodbController {

    @Resource
    private MongodbService mongodbService;

    @ApiOperation(value = "单文件上传")
    @PostMapping("uploadFile")
    public R<FileExportVo> uploadFile(MultipartFile file) {
        try {
            FileExportVo fileExportVo = mongodbService.uploadFile(file);
            return R.ok(fileExportVo);
        } catch (Exception e) {
            log.error("单文件上传", e);
            return R.fail();
        }
    }

    @ApiOperation(value = "多文件上传")
    @PostMapping("uploadFiles")
    public R<List<FileExportVo>> uploadFiles(MultipartFile[] files) {
        try {
            List<MultipartFile> multipartFiles = Arrays.asList(files);
            List<FileExportVo> list = mongodbService.uploadFiles(multipartFiles);
            return R.ok(list);
        } catch (Exception e) {
            log.error("多文件上传", e);
            return R.fail();
        }
    }

    @ApiOperation(value = "文件删除")
    @PostMapping("delFile")
    public R<T> delFile(String fileId) {
        try {
            mongodbService.removeFile(fileId);
            return R.ok();
        } catch (Exception e) {
            log.error("文件删除", e);
            return R.fail();
        }
    }

    @ApiOperation(value = "获取文件base64")
    @PostMapping("getFileBase64")
    public R<byte[]> getFileBase64(String fileId) {
        try {
            FileExportVo fileExportVo = mongodbService.downloadFile(fileId);
            return R.ok(fileExportVo.getData());
        } catch (Exception e) {
            log.error("获取文件base64", e);
            return R.fail();
        }
    }

}
