package com.persagy.dmp.file.controller;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.persagy.dmp.common.context.AppContext;
import com.persagy.dmp.common.lang.PsDateTime;
import com.persagy.dmp.common.model.response.CommonResult;
import com.persagy.dmp.common.utils.ResultHelper;
import com.persagy.dmp.file.model.FileInfo;
import com.persagy.dmp.file.model.FileInfoCreator;
import com.persagy.dmp.file.service.IFileService;
import com.persagy.dmp.storage.service.FileStorageFactory;
import com.persagy.dmp.storage.utils.FileStorageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * 文件管理Controller
 * @author Charlie Yu
 * @date 2021-05-15
 */
@RestController
@RequestMapping("/test")
public class TestController {

    @Autowired
    IFileService fileService;

    @PostMapping(value = "/uploadFile")
    @CrossOrigin
    public CommonResult<FileInfo> uploadFile(@RequestParam("file") MultipartFile multipartFile) throws IOException {
        String fileName = multipartFile.getResource().getFilename();
        FileInfo fileInfo = FileInfoCreator.of(AppContext.getContext().getGroupCode(),
                IdWorker.getIdStr(), "ADM", fileName);
        fileInfo.setCreationTime(new PsDateTime());
        // 可对fileInfo属性额外配置。如有效期等
        fileService.insertFile(fileInfo);
        FileStorageFactory.getService().upload(fileInfo.getFileBucket(), fileInfo.getFilePath(), multipartFile.getInputStream());
        return ResultHelper.single(fileInfo);
    }
}
