package com.dsk.web.controller.business;

import com.dsk.common.config.RuoYiConfig;
import com.dsk.common.core.controller.BaseController;
import com.dsk.common.core.domain.AjaxResult;
import com.dsk.common.utils.file.FileUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.List;

/**
 * @author lxl
 * @Description: 项目文件管理Controller
 * @Date 2023/5/30 上午 8:44
 **/
@Slf4j
@RestController
@RequestMapping("/business/file")
public class BusinessFileController extends BaseController {

    // 本地资源路径
    public static final String LOCALPATH = RuoYiConfig.getProfile();

    /**
     * 新建文件夹
     */
//    @PreAuthorize("@ss.hasPermi('system:file:add')")
//    @Log(title = "项目资料文档", businessType = BusinessType.INSERT)
    @GetMapping("/new/{filePath}")
    public AjaxResult newFolder(@PathVariable String filePath) {
        return FileUtils.newFolder(LOCALPATH + filePath) ? AjaxResult.success() : AjaxResult.error();
    }

    /**
     * 删除某个文件或整个文件夹
     */
    @GetMapping("/remove/{filePath}")
    public AjaxResult removeFile(@PathVariable String filePath) {
        boolean deleteFile = FileUtils.deleteFile(LOCALPATH + filePath);
        return deleteFile ? AjaxResult.success() : AjaxResult.error();
    }

    /**
     * 获取文件夹中所有文件
     */
    @GetMapping("/all/{folderPath}")
    public AjaxResult getAllFiles(@PathVariable String folderPath) {
        List<String> allFiles = FileUtils.getAllFiles(LOCALPATH + folderPath);
        return AjaxResult.success(allFiles);
    }

    /**
     * 上传文件及文件夹
     * @param url
     * @param folderPath
     * @return
     */
    @GetMapping("/upload/{url}/{folderPath}")
    public AjaxResult uploadFolder(@PathVariable("url") String url,@PathVariable("folderPath") String folderPath) throws IOException {
        return toAjax(FileUtils.uploadFolder(url, LOCALPATH + folderPath));
    }

    /**
     * 下载文件
     * @param url
     * @param targetFolder
     * @return
     */
    @GetMapping("/download/{url}/{targetFolder}")
    public AjaxResult downloadFolder(@PathVariable("url") String url,@PathVariable("targetFolder") String targetFolder) throws IOException {
        return toAjax(FileUtils.downloadFolder(url, targetFolder));
    }
}
