package com.app.util.file;

import cn.hutool.core.util.IdUtil;
import com.app.dto.FileDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.Optional;

/**
 * 功能描述：文件工具类
 *
 * @Auther: 梁展鹏
 * @Date: 2018/7/24 11:38
 */
@Slf4j
@Component
public class FileUtil {

    @Value("${file.path}")
    private String filePath;

    /**
     * 功能描述：上传文件
     *
     * @param file 文件
     * @return
     */
    public Optional<FileDto> upload(MultipartFile file) {
        if (file.isEmpty()) {
            log.error("文件为空", file.getOriginalFilename());
            return null;
        }

        String originalFileName = file.getOriginalFilename(); // 源文件名(包含后缀)
        String suffixName = originalFileName.substring(originalFileName.lastIndexOf("."));  // 源文件后缀名
        String newFileName = String.format("%s%s", IdUtil.randomUUID(), suffixName);

        File destFile = new File(filePath + File.separator + newFileName);
        if (!destFile.getParentFile().exists()) {
            destFile.getParentFile().mkdirs();
        }

        /* 保存文件 */
        try {
            file.transferTo(destFile);
            return Optional.of(new FileDto().setFileName(newFileName).setPath("/file/" + newFileName));
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 功能描述：获取文件后缀
     *
     * @param fileOriginName 源文件名
     * @return
     */
    public static String getSuffix(String fileOriginName) {
        return fileOriginName.substring(fileOriginName.lastIndexOf("."));
    }

    /**
     * 功能描述：
     *
     * @param file
     * @param request
     * @param response
     * @throws Exception
     */
    public void closeStream(File file, HttpServletRequest request, HttpServletResponse response) throws IOException {
        String fileName = file.getName();

        /* 清除buffer缓存 */
        response.reset();
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/octet-stream");
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
        response.setHeader("Cache-Control", "no-cache");

        /* 解决下载文件名乱码 */
        final String userAgent = request.getHeader("USER-AGENT");
        String finalFileName = null;
        if (userAgent.contains("MSIE")) { // IE浏览器
            finalFileName = URLEncoder.encode(fileName, "UTF8");
        } else if (userAgent.contains("Mozilla")) { // google,火狐浏览器
            finalFileName = new String(fileName.getBytes(), "ISO8859-1");
        } else {
            finalFileName = URLEncoder.encode(fileName, "UTF8"); // 其他浏览器
        }
        response.setHeader("Content-Disposition", "attachment;filename=" + finalFileName); // 这里设置一下让浏览器弹出下载提示框，而不是直接在浏览器中打开
        response.setHeader("Pragma", "no-cache");

        InputStream inputStream = new BufferedInputStream(new FileInputStream(file));
        byte[] buffer = new byte[inputStream.available()];
        inputStream.read(buffer);

        OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
        outputStream.write(buffer);
        outputStream.flush();
        outputStream.close();
        inputStream.close();
    }

}
