package com.xhpc.charging.station.utils.img;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * program: ruoyi
 * User: HongYun
 * Date:2021-10-09 10
 */
public class DownMaterialUtil {
    public static InputStream getInputStream(String urlImg) {

        InputStream inputStream = null;
        HttpURLConnection httpURLConnection = null;

        try {

            URL url = new URL(urlImg);
            httpURLConnection = (HttpURLConnection) url.openConnection();
            // 设置网络连接超时时间
            httpURLConnection.setConnectTimeout(3000);
            // 设置应用程序要从网络连接读取数据
            httpURLConnection.setDoInput(true);

            httpURLConnection.setRequestMethod("GET");
            int responseCode = httpURLConnection.getResponseCode();
            if (responseCode == 200) {
                // 从服务器返回一个输入流
                inputStream = httpURLConnection.getInputStream();

            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return inputStream;
    }

    public static void saveImageToDisk(List<String> urls, File file, List<String> imgNames) {

        for(int i = 0; i < urls.size(); i ++) {
            InputStream inputStream = getInputStream(urls.get(i));
            if (null == inputStream) continue;
            byte[] data = new byte[1024];
            int len = 0;
            FileOutputStream fileOutputStream = null;
            try {
                String str = imgNames.get(i);
                int poke = 0;
                for(int j = str.length() - 1; j >= 0; j --){
                    if(str.charAt(j) == 47){
                        poke = j;
                        break;
                    }
                }
                String real = str.substring(poke + 1);
                System.out.println(real);
                System.out.println(file.getName() + "/" + real);
                fileOutputStream = new FileOutputStream(file.getAbsoluteFile() + "/" + real);
                System.out.println(file.getAbsoluteFile());
                while ((len = inputStream.read(data)) != -1) {
                    fileOutputStream.write(data, 0, len);
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {

                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                if (fileOutputStream != null) {
                    try {
                        fileOutputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println("success");
            }
        }
    }

//    public static void saveImageToDisk1(List<String> urls, File file, List<String> imgNames) {
//
//        for (int i = 0; i < urls.size(); i++) {
//            InputStream inputStream = getInputStream(urls.get(i));
//            if(null == inputStream) continue;
//            System.out.println(inputStream);
//            byte[] data = new byte[1024];
//            int len = 0;
//            FileOutputStream fileOutputStream = null;
//            try {
//                String str = imgNames.get(i);
//                int poke = 0;
//                for (int j = str.length() - 1; j >= 0; j--) {
//                    if (str.charAt(j) == 47) {
//                        poke = j;
//                        break;
//                    }
//                }
//                String real = str.substring(poke + 1);
//                System.out.println(real);
//                System.out.println(file.getName() + "\\" + real);
//                fileOutputStream = new FileOutputStream(file.getAbsoluteFile() + "\\" + real);
//                while ((len = inputStream.read(data)) != -1) {
//                    fileOutputStream.write(data, 0, len);
//                }
//            } catch (IOException e) {
//                e.printStackTrace();
//            } finally {
//
//                try {
//                    inputStream.close();
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//                if (fileOutputStream != null) {
//                    try {
//                        fileOutputStream.close();
//                    } catch (IOException e) {
//                        e.printStackTrace();
//                    }
//                }
//                System.out.println("success");
//            }
//        }
//    }

    public static void fileToZip(File sourceFile) throws Exception {

        if (!sourceFile.exists()) {
            throw new RuntimeException("不存在");
        }
        if (!sourceFile.isDirectory()) {
            throw new RuntimeException("不是文件夹");
        }
        //zip文件生成位置
        File zipFile = new File(sourceFile.getAbsolutePath() + ".zip");
        FileOutputStream fos = new FileOutputStream(zipFile);
        ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(fos));
        fileToZip(zos, sourceFile, "");
        zos.close();
        fos.close();
    }

    public static void fileToZip(File sourceFile, String url) throws Exception {

        if (!sourceFile.exists()) {
            throw new RuntimeException("不存在");
        }
        if (!sourceFile.isDirectory()) {
            throw new RuntimeException("不是文件夹");
        }
        //zip文件生成位置
        File zipFile = new File(url + ".zip");
        FileOutputStream fos = new FileOutputStream(zipFile);
        ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(fos));
        fileToZip(zos, sourceFile, "");
        zos.close();
        fos.close();
    }
    private static void fileToZip(ZipOutputStream zos, File sourceFile, String path) throws Exception {

        //如果是文件夹只创建zip实体即可，如果是文件，创建zip实体后还要读取文件内容并写入
        if (sourceFile.isDirectory()) {
            path = path + sourceFile.getName() + "/";
            ZipEntry zipEntry = new ZipEntry(path);
            zos.putNextEntry(zipEntry);
            for (File file : Objects.requireNonNull(sourceFile.listFiles())) {
                fileToZip(zos, file, path);
            }
        } else {
            //创建ZIP实体，并添加进压缩包
            ZipEntry zipEntry = new ZipEntry(path + sourceFile.getName());
            zos.putNextEntry(zipEntry);
            byte[] bufs = new byte[1024 * 10];
            //读取待压缩的文件并写进压缩包里
            FileInputStream fis = new FileInputStream(sourceFile);
            BufferedInputStream bis = new BufferedInputStream(fis, 1024 * 10);
            int read = 0;
            while ((read = bis.read(bufs, 0, 1024 * 10)) != -1) {
                zos.write(bufs, 0, read);
            }
            bis.close();
            fis.close();
        }
    }

    public static void saveToFile(String targetUrl,String destUrl) {

        FileOutputStream fos = null;
        BufferedInputStream bis = null;
        HttpURLConnection httpUrl = null;
        URL url = null;
        int BUFFER_SIZE = 1024;
        byte[] buf = new byte[BUFFER_SIZE];
        int size = 0;
        try {
            url = new URL(targetUrl);
            httpUrl = (HttpURLConnection) url.openConnection();
            httpUrl.connect();
            bis = new BufferedInputStream(httpUrl.getInputStream());
            fos = new FileOutputStream(destUrl);
            while ((size = bis.read(buf)) != -1) {
                fos.write(buf, 0, size);
            }
            fos.flush();
        } catch (IOException | ClassCastException ignored) {
        } finally {
            try {
                if(null != fos) {
                    fos.close();
                }
                if(null != bis) {
                    bis.close();
                }
                if(null != httpUrl) {
                    httpUrl.disconnect();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    public static List<String> getDownLoadUrls(String left, List<String> imgUrl){
        List<String> res = new ArrayList<>();
        for (String s : imgUrl) {
            res.add(left + s);
        }
        return res;
    }

    /**
     * 以流的形式下载文件
     *
     * @param file
     * @param response
     * @return
     */
    public static HttpServletResponse downloadZip(File file, HttpServletResponse response) {
        try {
            // 以流的形式下载文件。
            InputStream fis = new BufferedInputStream(new FileInputStream(file.getPath()));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            // 清空response
            response.reset();
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            //如果输出的是中文名的文件，在此处就要用URLEncoder.encode方法进行处理
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(file.getName(), "UTF-8"));
            toClient.write(buffer);
            toClient.flush();
            toClient.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            try {
                File f = new File(file.getPath());
//                f.delete();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return response;
    }
}
