package com.jianshui.platform.utils;

import com.jianshui.common.constant.InvoiceCommonConstants;
import com.jianshui.platform.dto.DownLoadDTO;
import org.springframework.util.StringUtils;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * @Author: kane
 * @Description: 批量下载工具类
 * @CreateTime: 2023-06-09  15:46
 * @Version: 1.0
 **/
public class BatchDownloadUtils {

    /**
     * 功能描述: 批量下载
     *
     * @param status   文件类型0-pdf 1-ofd
     * @param downLoad
     * @return : void
     */
    public static void downloadAndZipFiles(List<DownLoadDTO> downLoad, String status, HttpServletResponse response) {
        //获取当前时间为包名
        Date now = new Date();
        SimpleDateFormat format = new SimpleDateFormat(InvoiceCommonConstants.DATEFORMAT);
        String name = format.format(now);
        String zipFileName = name + ".zip";
        OutputStream ops = null;
        ZipOutputStream zos = null;
        InputStream inputStream = null;
        try {
            //设置响应配置
            response.setHeader("Content-Disposition", "attachment;filename=" + zipFileName);
            response.setCharacterEncoding("utf-8");
            ops = response.getOutputStream();
            zos = new ZipOutputStream(ops);
            String fileName = "";
            for (DownLoadDTO downLoadDTO : downLoad) {
                String url = downLoadDTO.getUrl();
                if (StringUtils.hasText(url)) {
                    //将字符串地址转为url下载
                    URL downloadUrl = new URL(url);
                    //创建下载连接
                    HttpURLConnection httpConn = (HttpURLConnection) downloadUrl.openConnection();
                    //获取下载状态码
                    int responseCode = httpConn.getResponseCode();
                    if (responseCode == HttpURLConnection.HTTP_OK) {
                        //获取下载后文件名称
                        fileName = getFileName(httpConn, status, downLoadDTO.getFphm());
                        //读取流文件
                        inputStream = httpConn.getInputStream();
                        ZipEntry zipEntry = new ZipEntry(fileName);
                        zos.putNextEntry(zipEntry);
                        int bytesRead = -1;
                        byte[] buffer = new byte[4096];
                        while ((bytesRead = inputStream.read(buffer)) != -1) {
                            zos.write(buffer, 0, bytesRead);
                        }
                    }
                    //状态码为302重定向
                    if (responseCode == HttpURLConnection.HTTP_MOVED_TEMP) {
                        //获取重定向后的下载地址
                        String newUrl = httpConn.getHeaderField("Location");
                        URL urlNew = new URL(newUrl);
                        HttpURLConnection httpConnNew = (HttpURLConnection) urlNew.openConnection();
                        fileName = getFileName(httpConnNew, status, downLoadDTO.getFphm());
                        inputStream = httpConnNew.getInputStream();
                        ZipEntry zipEntry = new ZipEntry(fileName);
                        zos.putNextEntry(zipEntry);
                        int bytesRead = -1;
                        byte[] buffer = new byte[4096];
                        while ((bytesRead = inputStream.read(buffer)) != -1) {
                            zos.write(buffer, 0, bytesRead);
                        }
                        httpConnNew.disconnect();
                    }

                    httpConn.disconnect();
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (zos != null) {
                try {
                    zos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (ops != null) {
                try {
                    ops.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    /**
     * 功能描述: 获取下载后的文件名
     *
     * @param httpConn
     * @return : java.lang.String
     */
    private static String getFileName(HttpURLConnection httpConn, String status, String fphm) {
        String fileName = "";
        String disposition = httpConn.getHeaderField("Content-Disposition");
        if (disposition != null) {
            int index = disposition.indexOf("filename=");
            if (index > 0) {
                if (InvoiceCommonConstants.PDFSTATUS.equals(status)) {
                    fileName = fphm + ".pdf";
                } else {
                    fileName = fphm + ".ofd";
                }
            }
        }
        if (StringUtils.isEmpty(fileName)) {
            if (InvoiceCommonConstants.PDFSTATUS.equals(status)) {
                fileName = fphm + ".pdf";
            } else {
                fileName = fphm + ".ofd";
            }
        }
        return fileName;
    }
}
