package ink.wgink.module.file.service.filecenter.impl;

import ink.wgink.common.base.DefaultBaseService;
import ink.wgink.exceptions.SearchException;
import ink.wgink.module.file.enums.UploadTypeEnum;
import ink.wgink.module.file.pojo.dtos.v2.FileUploadSuccessDTO;
import ink.wgink.module.file.pojo.vos.v2.FileSaveVO;
import ink.wgink.module.file.service.filecenter.IFileCenterService;
import ink.wgink.module.file.service.v2.IFileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;

/**
 * @ClassName: FileCenterServiceImpl
 * @Description: 文件中心
 * @Author: wanggeng
 * @Date: 2022/8/6 13:36
 * @Version: 1.0
 */
@Service
public class FileCenterServiceImpl extends DefaultBaseService implements IFileCenterService {

    @Autowired
    private IFileService fileService;

    @Override
    public FileUploadSuccessDTO uploadSingleByUserId(String userId, MultipartFile uploadFile, UploadTypeEnum uploadTypeEnum) {
        FileSaveVO fileSaveVO = getCenterFileSaveVO(uploadFile, uploadTypeEnum, userId);
        return fileService.saveFile(fileSaveVO);
    }

    @Override
    public void download(HttpServletRequest request, HttpServletResponse response, String fileId) {
        fileService.download(request, response, fileId);
    }

    /**
     * 获取文件保存VO
     *
     * @param uploadFile
     * @param uploadTypeEnum
     * @return
     */
    private FileSaveVO getCenterFileSaveVO(MultipartFile uploadFile, UploadTypeEnum uploadTypeEnum, String creator) {
        String fileName = uploadFile.getOriginalFilename();
        InputStream inputStream;
        try {
            inputStream = uploadFile.getInputStream();
        } catch (IOException e) {
            throw new SearchException(e);
        }
        return fileService.getCenterFileSaveVO(inputStream, uploadTypeEnum, fileName, creator);
    }

}
