package com.ruoyi.ibs.task.controller;

import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.system.domain.OssFileUploadDTO;
import com.ruoyi.system.service.OssFileService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.SneakyThrows;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;

/**
 * @Author 吴凯程
 * @Date 2025/6/16
 **/
@Api(tags = "OSS文件上传")
@RestController
@RequestMapping("/oss")
public class OssController {

    @Resource
    private OssFileService ossFileService;

    @Anonymous
    @ApiOperation("上传")
    @PostMapping("/upload")
    public AjaxResult uploadFileToOss(OssFileUploadDTO ossFileUploadDTO) {
//        MultipartFile file = ImageUtils.compressPictureForScale(ossFileUploadDTO.getFile(), 512);
//        ossFileUploadDTO.setFile(file);
        // 根据当前用户的身份设置用户名，匿名用户使用默认用户名
        if (SecurityUtils.getAuthentication().getPrincipal().equals("anonymousUser")){
            ossFileUploadDTO.setUserName("999");
        }else {
            ossFileUploadDTO.setUserName(SecurityUtils.getUsername());
        }
        return AjaxResult.success("文件上传成功: " + ossFileService.uploadFileToOss(ossFileUploadDTO));
    }

    @SneakyThrows
    @Anonymous
    @ApiOperation("下载")
    @GetMapping("/download")
    public ResponseEntity<InputStreamResource> downloadFile(HttpServletRequest request, @RequestParam String uuid) {
        MultipartFile file = ossFileService.getFileFromOss(uuid);
        InputStream inputStream = file.getInputStream();
        // 处理特殊字符
        String encodedFileName = FileUtils.setFileDownloadHeader(request, file.getName());
        StringBuilder contentDispositionValue = new StringBuilder();
        contentDispositionValue.append("attachment; filename=")
                .append(encodedFileName)
                .append(";")
                .append("filename*=")
                .append("utf-8''")
                .append(encodedFileName);
        InputStreamResource resource = new InputStreamResource(inputStream);

        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.CONTENT_DISPOSITION, contentDispositionValue.toString());
        headers.add(HttpHeaders.CONTENT_TYPE, "application/octet-stream");
        return ResponseEntity.ok().headers(headers).body(resource);
    }



}
