package com.CUST.brain.web.controller.system;

import com.CUST.brain.common.api.CommonResult;
import com.CUST.brain.common.utils.OssUtil;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@RestController
@RequestMapping("/oss")
public class OssController {

    @Resource
    private OssUtil ossUtil;

    @PostMapping("/upload")
    public CommonResult<String> uploadFile(@RequestParam("file") MultipartFile file,
                                           @RequestParam(value = "type", required = false, defaultValue = "img") String type) {
        String ext = "";
        String originalName = file.getOriginalFilename();
        if (originalName != null && originalName.lastIndexOf(".") != -1) {
            ext = originalName.substring(originalName.lastIndexOf("."));
        }
        String datePath = new SimpleDateFormat("yyyy/MM/dd").format(new Date());
        String folder;
        switch (type) {
            case "doc": folder = "doc"; break;
            case "video": folder = "video"; break;
            case "avatar": folder = "avatar"; break;
            case "other": folder = "other"; break;
            default: folder = "img";
        }
        String objectName = folder + "/" + datePath + "/" + UUID.randomUUID() + ext;
        String url = ossUtil.upload(file, objectName);
        if (url != null) {
            return CommonResult.success(url, "上传成功");
        } else {
            return CommonResult.failed("上传失败");
        }
    }
} 