package org.dromara.x.file.storage.controller;

import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.exception.file.FileNameLengthLimitExceededException;
import com.ruoyi.common.core.exception.file.InvalidExtensionException;
import com.ruoyi.common.core.utils.file.FileUtils;
import com.ruoyi.common.core.utils.file.MimeTypeUtils;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.file.utils.FileUploadUtils;
import com.ruoyi.system.api.domain.SysFile;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.dromara.x.file.storage.core.FileInfo;
import org.dromara.x.file.storage.core.FileStorageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Objects;

@Slf4j
@RestController
public class FileDetailController {

    @Autowired
    private FileStorageService fileStorageService;//注入实列

    /**
     * 文件上传请求
     */
    @PostMapping("upload")
    public R<SysFile> upload(@RequestParam("file") MultipartFile file, @RequestParam(value = "uploadBasePath", required = false) String uploadBasePath) throws InvalidExtensionException {
        int fileNamelength = Objects.requireNonNull(file.getOriginalFilename()).length();
        if (fileNamelength > FileUploadUtils.DEFAULT_FILE_NAME_LENGTH)
        {
            throw new FileNameLengthLimitExceededException(FileUploadUtils.DEFAULT_FILE_NAME_LENGTH);
        }
        FileUploadUtils.assertAllowed(file, MimeTypeUtils.NO_ZIP_ALLOWED_EXTENSION);
        try
        {
            FileInfo fileInfo = fileStorageService.of(file)
                    .setSaveFilename(FileUploadUtils.extractFilename(file))
                    .putAttr("uploadBasePath", uploadBasePath)
                    .upload();  //将文件上传到对应地方
            SysFile sysFile = new SysFile();
            sysFile.setName(fileInfo.getUrl());
            sysFile.setUrl(fileInfo.getUrl());
            return R.ok(sysFile);
        }
        catch (Exception e)
        {
            log.error("上传文件失败", e);
            return R.fail(e.getMessage());
        }
    }

    @GetMapping("/download/{filename}")
    public void downloadFile(@PathVariable String filename, HttpServletResponse response) throws IOException {
        // 获取文件信息
        FileInfo fileInfo = fileStorageService.getFileInfoByUrl(filename);
        // 下载文件
        byte[] data =  fileStorageService.download(fileInfo).bytes();
        response.reset();
        response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
        response.addHeader("Content-Length", String.valueOf(data.length));
        response.setContentType("application/octet-stream; charset=UTF-8");
        IOUtils.write(data, response.getOutputStream());
    }

    @DeleteMapping("/delete/{filename}")
    public AjaxResult deleteFile(@PathVariable String filename) {
        fileStorageService.delete(filename);
        return AjaxResult.success();
    }

    @DeleteMapping("/batchDelete/{filenames}")
    public AjaxResult deleteFiles(@PathVariable List<String> filenames) {
        for (String filename : filenames) {
            fileStorageService.delete(filename);
        }
        return AjaxResult.success();
    }
}
