package com.ruoyi.web.controller.open;

import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.file.request.UploadForwardReq;
import com.ruoyi.file.request.UploadRedirectReq;
import com.ruoyi.file.object.UploadResp;
import com.ruoyi.file.service.FileService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

/**
 * 文件接口
 * 
 * @author ruoyi
 */
@Api(tags = "文件接口")
@RestController
@RequestMapping("/open/file")
public class OpenFileController
{
    private static final Logger log = LoggerFactory.getLogger(OpenFileController.class);

    @Autowired
    private FileService fileService;

    private static final String FILE_DELIMETER = ",";

    /**
     * 通用下载请求
     * 
     * @param fileName 文件名称
     * @param delete 是否删除
     */
    @GetMapping("/download")
    public void fileDownload(String fileName, Boolean delete, HttpServletResponse response, HttpServletRequest request)
    {
        try
        {
            if (!FileUtils.checkAllowDownload(fileName))
            {
                throw new Exception(StringUtils.format("文件名称({})非法，不允许下载。 ", fileName));
            }
            String realFileName = System.currentTimeMillis() + fileName.substring(fileName.indexOf("_") + 1);
            String filePath = RuoYiConfig.getDownloadPath() + fileName;

            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, realFileName);
            FileUtils.writeBytes(filePath, response.getOutputStream());
            if (delete)
            {
                FileUtils.deleteFile(filePath);
            }
        }
        catch (Exception e)
        {
            log.error("下载文件失败", e);
        }
    }

    /**
     * 仅上传（单个）
     */
    @ApiOperation("仅上传")
    @PostMapping("/upload/{token}/{directory}")
    public AjaxResult upload(@PathVariable String token, @PathVariable String directory, MultipartFile file)
    {
        UploadResp upload = fileService.upload(file, directory, token);
        return AjaxResult.success(upload);
    }

    /**
     * 上传并转发（单个）
     */
    @ApiOperation("上传并转发")
    @PostMapping("/uploadForward/{token}/{directory}")
    public String uploadForward(@PathVariable String token, @PathVariable String directory, MultipartFile file, @Valid UploadForwardReq req, HttpServletRequest request, HttpServletResponse response)
    {
        return fileService.uploadForward(file, directory, token, req, request, response);
    }

    /**
     * 上传并重定向（单个）
     */
    @ApiOperation("上传并重定向")
    @PostMapping("/uploadRedirect/{token}/{directory}")
    public void uploadRedirect(@PathVariable String token, @PathVariable String directory, MultipartFile file, @Valid UploadRedirectReq req, HttpServletRequest request, HttpServletResponse response)
    {
        fileService.uploadRedirect(file, directory, token, req, request, response);
    }
}
