package com.kiisoo.ic.activity.controller;

import com.kiisoo.ic.common.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.util.Map;
import java.util.UUID;

@RestController
@Api(value = "后台-上传文件", tags = {"后台-上传文件"})
@Slf4j
public class FileController extends BaseController {

    @ApiOperation(value = "上传文件")
    @PostMapping(value = "/upload")
    public Map<String, Object> upload(@RequestParam(value = "file", required = false) MultipartFile file) {
        if (file == null) return fail();
        String fileName = file.getOriginalFilename();
        if (fileName == null) return fail();
        fileName = renameToUUID(fileName);
        try {
            File targetPath = new File("upload");
            if (!targetPath.exists()) {
                boolean state = targetPath.mkdirs();
            }
            FileOutputStream out = new FileOutputStream("upload/" + fileName);
            out.write(file.getBytes());
            out.flush();
            out.close();
        } catch (Exception e) {
            log.error("上传出错", e);
            return fail();
        }
        return data("/upload/" + fileName);
    }

    private String renameToUUID(String filename) {
        return UUID.randomUUID() + "." + filename.substring(filename.lastIndexOf(".") + 1);
    }
}
