package com.yeejoin.amos.fas.business.util;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * 文件下载 工具类
 *
 * @author 郑嘉伟
 * @since 2020-08-05
 */
public class FileUtils {

    private static final Logger logger = LogManager.getLogger(FileUtils.class);

    /**
     * 获取压缩好zip——>设置消息头——>输出
     * @param response
     * @param list
     * @param ipUrl
     * @throws IOException
     */
    public static void downloadZIP(HttpServletResponse response, List<String> list, String ipUrl) throws IOException {
        //构建zip
        String zipname = "单据相关附件.zip";
        String zippath = fileToZip(list, zipname, ipUrl);

        OutputStream out = null;
        BufferedInputStream br = null;
        try {
            String fileName = new String(zipname.getBytes("UTF-8"), "iso-8859-1");
            br = new BufferedInputStream(new FileInputStream(zippath));
            byte[] buf = new byte[1024];
            int len = 0;
            response.reset();
            response.setHeader("Content-Type", "application/octet-stream;charset=utf-8");
            response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
            response.setHeader("Access-Control-Expose-Headers", "access_token");
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setContentType("application/zip");
            out = response.getOutputStream();
            while ((len = br.read(buf)) > 0) {
                out.write(buf, 0, len);
                out.flush();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            br.close();
            out.close();
        }
    }

    /**
     * 通过文件服务器——>获取流——>输出——>压缩
     *
     * @param list
     * @param fileName
     * @return
     */
    public static String fileToZip(List<String> list, String fileName, String ipUrl) {
        // 临时目录
        String path = System.getProperty("java.io.tmpdir") + fileName;
        File zipFile = new File(path);
        zipFile.deleteOnExit();
        try {
            zipFile.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        InputStream fis = null;
        BufferedInputStream bis = null;
        try (
             FileOutputStream fos = new FileOutputStream(zipFile);
             ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(fos));) {
            byte[] bufs = new byte[1024 * 10];
            for (String a : list) {
                fis = getInputStreamFromURL(ipUrl + a);

                String subFileName = new File(ipUrl + a).getName();
                //创建ZIP实体，并添加进压缩包
                ZipEntry zipEntry = new ZipEntry(subFileName);
                zos.putNextEntry(zipEntry);

                bis = new BufferedInputStream(fis, 1024 * 10);
                int read = 0;
                while ((read = bis.read(bufs, 0, 1024 * 10)) != -1) {
                    zos.write(bufs, 0, read);
                }
            }
            System.out.println("压缩成功");
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        } finally {
            try {
                if (null != bis) {
                    bis.close();
                }
                if (null != fis) {
                    fis.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return path;
    }


    /**
     * 从URL中读取图片,转换成流形式.
     *
     * @param destUrl
     * @return
     */
    public static InputStream getInputStreamFromURL(String destUrl) {

        HttpURLConnection httpUrl = null;
        URL url = null;
        InputStream in = null;
        try {
            url = new URL(destUrl);
            httpUrl = (HttpURLConnection) url.openConnection();
            httpUrl.connect();
            in = httpUrl.getInputStream();
            return in;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}