package com.greenorange.promotion.controller.fileInfo;

import com.greenorange.promotion.common.BaseResponse;
import com.greenorange.promotion.common.ResultUtils;
import com.greenorange.promotion.model.dto.fileInfo.UploadFileRequest;
import com.greenorange.promotion.service.file.FileInfoService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.constraints.NotBlank;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;


/**
 * 文件 控制器
 */
@RestController
@RequestMapping("file")
@Slf4j
@Tag(name = "文件管理")
@Transactional
public class FileInfoController {


    @Resource
    private FileInfoService fileInfoService;




    /**
     * Web端文件上传(服务器）
     * @param uploadFileRequest 业务请求
     * @param multipartFile 上传的文件
     * @return 上传文件的路径
     */
    @PostMapping("upload")
    @Operation(summary = "Web端文件上传（服务器）", description = "参数：文件添加请求体，权限：管理员，方法名：addFileInfo")
    public BaseResponse<String> uploadFile(@RequestPart("file") MultipartFile multipartFile, UploadFileRequest uploadFileRequest) throws IOException{
        // 校验文件
        fileInfoService.validFile(multipartFile, uploadFileRequest);
        // 文件上传
        String view = fileInfoService.uploadFile(multipartFile, uploadFileRequest);
        return ResultUtils.success(view, "上传成功");
    }





    /**
     * 文件下载（服务器）
     * @param fileName	文件名
     * @throws IOException
     */
    @GetMapping("/download/{fileName}")
    @Operation(summary = "文件下载（服务器）", description = "参数：文件名，权限：所有人，方法名：downloadFile")
    public void downloadFile(@PathVariable @NotBlank String fileName, HttpServletResponse response) throws IOException {
        fileInfoService.downloadFile(fileName, response);
    }

}