package shop.alien.store.controller;

import io.swagger.annotations.Api;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import shop.alien.util.common.FileUpload;

import java.util.HashMap;
import java.util.Map;

/**
 * 文件上传
 */
@Api(tags = {"一期-文件上传"})
@Slf4j
@CrossOrigin
@RestController
@RequestMapping("/upload")
@RequiredArgsConstructor
public class FileUploadController {

    private final FileUpload fileUpload;

    @PostMapping("file")
    public Map<String, Object> addOrUpdateAppeal(@RequestParam(value = "file", required = false) MultipartFile image1) {
        log.info("FileUploadController.addOrUpdateAppeal?fileName={}", image1.getOriginalFilename());
        Map<String, Object> response = new HashMap<>();
        try {
            String path = "";
            if (image1 != null && !StringUtils.isEmpty(image1.getOriginalFilename())) {
                path = fileUpload.saveImage(image1);
            }
            response.put("success", "上传成功");
            response.put("filePath", "https://www.ailien.shop:8080/" + path);
        } catch (Exception e) {
            log.error("FileUploadController.addOrUpdateAppeal error: " + e.getMessage());
            response.put("success", "上传失败");
            return response;
        }
        return response;
    }
}
