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

import cn.hutool.core.date.DateUtil;
import org.springframework.core.env.Environment;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
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
 */
@Component
public class DownMaterialUtil {

    @Resource
    private Environment environment;

    public static InputStream getInputStream(String urlImg) {

        InputStream inputStream = null;
        HttpURLConnection httpURLConnection;

        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;
    }

    /**
     * 保存图片到磁盘上
     *
     * @param urls
     * @param file
     * @param imgNames
     */
    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();
                System.out.println("下载出错了");
            } finally {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                if (fileOutputStream != null) {
                    try {
                        fileOutputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
    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();
        }
    }

    /**
     * 拼接图片前缀和后缀，最终生成完整的下载路径
     *
     * @param imgUrls      图片后缀集合
     * @param imgPrefixUrl 图片前缀
     * @return List<String> 完整图片集合
     * <p>
     * @author WH
     * @date 2021/11/25 14:19
     * @since version-1.0
     */
    public static List<String> getDownLoadUrls(String imgPrefixUrl, List<String> imgUrls) {

        List<String> res = new ArrayList<>();
        for (String s : imgUrls) {
            res.add(imgPrefixUrl + s);
        }
        return res;
    }

    /**
     * 负责定时删除服务器上面下载下来的二维码压缩包
     * 每天早上4点执行
     *
     * @author WH
     * @date 2021/11/24 15:50
     * @since version-1.0
     */
    @Scheduled(cron = "0 0 4 * * ?")
    public void deleteZips() {

        System.out.println(DateUtil.now() + " " + "二维码压缩包清理程序启动");
        //遍历指定文件夹下的所有图片 dist
        String zipLocation = environment.getProperty("zipLocation");
        if (zipLocation == null) {
            throw new RuntimeException("bootstrap.yml文件中的zipLocation位置不对，请检查");
        }
        File zipDirectory = new File(zipLocation);
        File[] zipFile = zipDirectory.listFiles();
        if (zipFile == null) {
            System.out.println("没有二维码压缩包可以删除");
            return;
        }
        for (File file : zipFile) {
            if (file.getName().contains("QRcodeMaterial")) {
                file.delete();
                System.out.println(DateUtil.now() + " " + file.getName() + "已被删除");
            }
        }
        System.out.println(DateUtil.now() + " " + "二维码压缩包清理程序结束");
    }
}
