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.core.domain.entity.BusinessFileVo;
import com.dsk.common.core.page.TableDataInfo;
import com.dsk.common.utils.StringUtils;
import com.dsk.common.utils.file.FileUploadUtils;
import com.dsk.common.utils.file.FileUtils;
import com.dsk.framework.config.ServerConfig;
import com.dsk.system.domain.BusinessIdDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

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

    @Autowired
    private ServerConfig serverConfig;

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

    /**
     * 删除某个文件或整个文件夹
     */
    @PostMapping("/remove")
    public AjaxResult removeFile(@RequestBody(required=false) BusinessIdDto filePath) {
        return FileUtils.delFolder(filePath.getFilePath()) ? AjaxResult.success() : AjaxResult.error();
    }

    /**
     * 分页查询项目的所有文件
     * 获取文件夹中所有文件
     */
    @GetMapping(value = "/list")
    public TableDataInfo getAllFiles(BusinessIdDto filePath) {
        startPage();
        List<BusinessFileVo> allFiles;
        if(StringUtils.isNumeric(filePath.getFilePath())) filePath.setFilePath(RuoYiConfig.getProfile() + filePath.getFilePath());
        allFiles = FileUtils.getAllFiles(filePath.getFilePath());
        //模糊查询文件
        if(StringUtils.isNotEmpty(filePath.getKeyword())){
            List<BusinessFileVo> allFileName = FileUtils.getAllFileNames(filePath.getFilePath());
            allFiles = allFileName.stream().filter(p -> p.getFilePath().contains(filePath.getKeyword())).collect(Collectors.toList());
        }
        return getDataTable(allFiles);
    }

    /**
     * 上传文件及文件夹
     * @param file 文件流
     * @param request 请求头参数
     * @return
     */
    @PostMapping("/upload")
    public AjaxResult uploadFolder(@RequestPart("file") MultipartFile file, HttpServletRequest request) {
        try {
            //获取文件名
            String filename = file.getOriginalFilename();
            String businessFileName = request.getHeader("FilePath");
            // 上传文件路径
            String filePath = RuoYiConfig.getUploadPath() + businessFileName + "/";

            //校验是否上传同名文件
            File newFile = new File(filePath);
            if (newFile.exists()) {
                // 获取当前目录下的文件和文件夹
                File[] files = newFile.listFiles();
                for (File allFile : files) {
                    if (filename.equals(allFile.getName())) return error("文件已存在");
                }
            }

            // 上传并返回文件全路径
            String fileName = FileUploadUtils.upload(filePath, file);
//            String url = serverConfig.getUrl() + fileName;
            AjaxResult ajax = AjaxResult.success();
            ajax.put("url", fileName);
            return ajax;
        } catch (IOException e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 下载文件
     * @param filePath 要下载的文件路径
     * @param response 返回的响应
     */
    @PostMapping("/download")
    public void downloadFolder(@RequestBody BusinessIdDto filePath, HttpServletResponse response) {
        FileUtils.downloadByFilePath(filePath.getFilePath(),response);
    }
}
