package com.keyware.shandan.common.util;

import org.springframework.util.Assert;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;

/**
 * 文件下載工具类
 */
public class FileDownload {
    /**
     * @param response HttpServletResponse
     * @param file     File
     * @return 结果
     */
    public static String download(HttpServletResponse response, File file) {
        return download(response, file, null, false);
    }

    /**
     * @param response HttpServletResponse
     * @param file     File
     * @param fileName 输出的文件名
     * @return 结果
     */
    public static String download(HttpServletResponse response, File file, String fileName) {
        return download(response, file, fileName, false);
    }

    /**
     * @param response HttpServletResponse
     * @param file     File
     * @param delete   下载完成后是否删除源文件
     * @return 结果
     */
    public static String download(HttpServletResponse response, File file, boolean delete) {
        return download(response, file, null, delete);
    }

    /**
     * @param response HttpServletResponse
     * @param file     File
     * @param fileName 输出的文件名称
     * @param delete   下载完成后是否删除源文件
     * @return 结果
     */
    public static String download(HttpServletResponse response, File file, String fileName, boolean delete) {
        Assert.notNull(response, "response is null.");
        Assert.notNull(file, "file is null.");
        Assert.isTrue(file.exists(), "没有在文件系统中找到该文件.");

        response.reset();
        response.setContentType("application/octet-stream");
        response.setCharacterEncoding("utf-8");
        response.setContentLength((int) file.length());

        if (!StringUtils.hasText(fileName)) {
            fileName = file.getName();
        }

        // 解决下载文件时文件名乱码问题
        byte[] fileNameBytes = fileName.getBytes(StandardCharsets.UTF_8);
        String outputName = new String(fileNameBytes, 0, fileNameBytes.length, StandardCharsets.ISO_8859_1);
        response.setHeader("Content-Disposition", "attachment;filename=" + outputName);

        try (OutputStream os = response.getOutputStream();
             BufferedInputStream bis = new BufferedInputStream(Files.newInputStream(file.toPath()))) {
            byte[] buff = new byte[1024];
            int i = 0;
            while ((i = bis.read(buff)) != -1) {
                os.write(buff, 0, i);
                os.flush();
            }
        } catch (IOException e) {
            return "下载过程出现错误，文件流读取异常！";
        } finally {
            if (delete) {
                if(file.exists()){
                    file.delete();
                }
            }
        }
        return "下载完成";
    }
}
