package com.yiboshi.science.utils;

import com.baomidou.mybatisplus.core.toolkit.IOUtils;
import org.springframework.http.ContentDisposition;
import org.springframework.http.MediaType;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.InputStream;
import java.io.OutputStream;

public class FileDownloadUtil {

    private static final MediaType MS_DOWNLOAD = new MediaType("application", "x-msdownload");

    public static void download(InputStream inputStream, HttpServletRequest request, HttpServletResponse response,
                                String fileName){
        BufferedInputStream br = null;
        OutputStream out = null;
        try{
            boolean isIE = isIE(request);
            //必须
            response.setCharacterEncoding("utf-8");
            response.setContentType(isIE ? MS_DOWNLOAD.toString() : MediaType.APPLICATION_OCTET_STREAM.toString());
            response.addHeader("Content-Disposition", ContentDisposition.builder("attachment")
                    .filename(fileName)
                    .build().toString());
            br = new BufferedInputStream(inputStream);
            out = response.getOutputStream();
            int len;
            byte[] buf = new byte[1024];
            while ((len = br.read(buf)) > 0){
                out.write(buf, 0, len);
            }
        } catch (Exception e){
            e.printStackTrace();
        } finally {
            IOUtils.closeQuietly(br);
            IOUtils.closeQuietly(out);
        }
    }

    public static boolean isIE(HttpServletRequest request) {
        String[] IEBrowserSignals = {"MSIE", "Trident", "Edge"};
        String userAgent = request.getHeader("User-Agent");
        for (String signal : IEBrowserSignals) {
            if (userAgent.contains(signal)){
                return true;
            }
        }
        return false;
    }
}

