package com.energy.manage.common.util;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class DownLoadUtil {

  /**
   * 批量下载文件至zip
   *
   * @param urlList
   * @param downloadName
   * @param request
   * @param response
   * @throws Exception
   */
  public static void downloadFiles2Zip(List<String> urlList,
                                       String downloadName,
                                       HttpServletRequest request,
                                       HttpServletResponse response) throws Exception {
    //响应头的设置
    response.reset();
    response.setCharacterEncoding("utf-8");
    response.setContentType("multipart/form-data");
    //设置压缩包的名字
    downloadName += ".zip";
    //返回客户端浏览器的版本号、类型
    String agent = request.getHeader("USER-AGENT");
    try {
      //针对IE或者以IE为内核的浏览器：
      if (agent.contains("MSIE") || agent.contains("Trident")) {
        downloadName = java.net.URLEncoder.encode(downloadName, "UTF-8");
      } else {
        //非IE浏览器的处理：
        downloadName = new String(downloadName.getBytes("UTF-8"), "ISO-8859-1");
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
    response.setHeader("Content-Disposition", "attachment;fileName=\"" + downloadName + "\"");
    //设置压缩流：直接写入response，实现边压缩边下载
    ZipOutputStream zipos = null;
    try {
      zipos = new ZipOutputStream(new BufferedOutputStream(response.getOutputStream()));
      zipos.setMethod(ZipOutputStream.DEFLATED); //设置压缩方法
    } catch (Exception e) {
      e.printStackTrace();
    }
    //循环将文件写入压缩流
    DataOutputStream os = null;
    for (String item : urlList) {
      HttpURLConnection conn = null;
      try {
        URL url = new URL(item);
        conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setRequestProperty("Connection", "Keep-Alive");
        int responseCode = conn.getResponseCode();
        if (responseCode != HttpURLConnection.HTTP_OK) {
          throw new Exception("文件已不存在");
        }
        //添加ZipEntry，并ZipEntry中写入文件流
        String fileName = URLDecoder.decode(item, "UTF-8");
        fileName = "素材" + File.separator + fileName.substring(fileName.lastIndexOf("/") + 1);
        zipos.putNextEntry(new ZipEntry(fileName));
        os = new DataOutputStream(zipos);
        InputStream is = conn.getInputStream();
        byte[] b = new byte[100];
        int length = 0;
        while ((length = is.read(b)) != -1) {
          os.write(b, 0, length);
        }
        is.close();
        zipos.closeEntry();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
    //关闭流
    try {
      os.flush();
      os.close();
      zipos.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}
