package com.ruoyi.web.controller;

import cn.dev33.satoken.annotation.SaIgnore;
import cn.hutool.core.util.ObjectUtil;
import com.ruoyi.common.annotation.Dev;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.system.service.ISysOssService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@RequiredArgsConstructor
@RestController
@RequestMapping("/")
public class UploadController {
    private final ISysOssService iSysOssService;


    @Log(title = "OSS对象存储", businessType = BusinessType.INSERT)
    @PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public R upload(@RequestPart("file") MultipartFile file, String pre) {
        if (ObjectUtil.isNull(file)) {
            throw new ServiceException("文件为空");
        }
        return R.ok(iSysOssService.upload(file, pre));
    }

    @Log(title = "OSS对象存储", businessType = BusinessType.INSERT)
    @PostMapping(value = "/uploadImg", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public R uploadImg(@RequestPart("file") MultipartFile file, String pre) {
      if (ObjectUtil.isNull(file)) {
        throw new ServiceException("文件为空");
      }
      if(!file.getContentType().startsWith("image/")){
        throw new ServiceException("不是图片");
      }
      return R.ok(iSysOssService.uploadImgs(file, pre));
    }

    /**
     * 下载OSS对象
     *
     * @param ossId OSS对象ID
     */
    @PostMapping("/download/{ossId}")
    public void download(@PathVariable Long ossId, HttpServletResponse response) throws IOException {
        iSysOssService.download(ossId, response);
    }
}
