package com.ruoyi.web.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.web.domain.FileInfo;
import com.ruoyi.web.service.IFileInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.Cleanup;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

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

@RestController
@RequestMapping("file")
@Api(tags = "附件相关")
public class FileController extends BaseController {

    private IFileInfoService fileInfoService;
    @Autowired
    public void setFileInfoService(IFileInfoService fileInfoService) {
        this.fileInfoService = fileInfoService;
    }

    @PostMapping("upload")
    @ApiOperation("文件上传")
    public AjaxResult upload(@RequestParam("file") MultipartFile file) throws Exception {
        String md5 = getMd5(file);

        QueryWrapper<FileInfo> qw = new QueryWrapper<>();
        qw.lambda().eq(FileInfo::getMd5,md5);
        FileInfo fileInfo = fileInfoService.getOne(qw);

        if (Objects.nonNull(fileInfo)) return success(fileInfo);

        fileInfo = new FileInfo();
        fileInfo.setName(file.getOriginalFilename());
        fileInfo.setType(file.getContentType());
        fileInfo.setSize(file.getSize());
        fileInfo.setMd5(md5);

        String filePath = RuoYiConfig.getUploadPath();
        String fileName = FileUploadUtils.upload(filePath, file);
        fileInfo.setPath(fileName);

        fileInfoService.save(fileInfo);
        return success(fileInfo);
    }

    private String getMd5(MultipartFile file) {
        try {
            @Cleanup
            InputStream inputStream = file.getInputStream();
            return DigestUtils.md5DigestAsHex(inputStream);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @GetMapping("{id}")
    @ApiOperation("文件下载")
    public void download(@PathVariable Long id, HttpServletResponse response) throws Exception {
        FileInfo fileInfo = fileInfoService.getById(id);
        String path = fileInfo.getPath();

        String localPath = RuoYiConfig.getProfile();
        String downloadPath = localPath + FileUtils.stripPrefix(path);
        response.setContentType(fileInfo.getType());
        FileUtils.writeBytes(downloadPath, response.getOutputStream());
    }

    @DeleteMapping("{id}")
    @ApiOperation("文件删除")
    public AjaxResult delete(@PathVariable Long id) {
        FileInfo fileInfo = fileInfoService.getById(id);
        String path = fileInfo.getPath();
        String localPath = RuoYiConfig.getProfile();
        String absPath = localPath + FileUtils.stripPrefix(path);
        FileUtils.deleteFile(absPath);
        fileInfoService.removeById(id);
        return success();
    }

}
