package com.zzsn.knowbase.util;


import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * @Description
 * @ClassName ZipUtils
 * @Author yuhuofei
 * @Date 2022/8/10 20:37
 * @Version 1.0
 */
@Slf4j
public class ZipUtils {

    /**
     * @param zipPathDir  压缩包路径 ，如 /home/data/zip-folder/
     * @param zipFileName 压缩包名称 ，如 测试文件.zip
     * @param fileList    要压缩的文件列表（绝对路径），如 /home/person/test/测试.doc，/home/person/haha/测试.doc
     * @return
     */
    public static void compressFiles(String zipPathDir, String zipFileName, List<String> fileList) {

        try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(new File(zipPathDir + zipFileName+".zip")))) {
            File zipFile = new File(zipPathDir);
            if (!zipFile.exists()) {
                zipFile.mkdirs();
            }
            for (String filePath : fileList) {
                log.info("file package file :{}",filePath);
                File file = new File(filePath);

                if (file.exists()) {
                    int index = file.getName().lastIndexOf('.');
                    ZipEntry zipEntry = new ZipEntry(file.getName().substring(0, index) + "-" + dateRandom18() + file.getName().substring(index));
                    zos.putNextEntry(zipEntry);
                    byte[] buffer = new byte[2048];
                    compressSingleFile(file, zos, buffer);
                }
            }
            zos.flush();
        } catch (Exception e) {
            log.error("压缩所有文件成zip包出错{}" , e.getMessage());
        }
    }

    //压缩单个文件
    public static void compressSingleFile(File file, ZipOutputStream zos, byte[] buffer) {
        int len;
        try (FileInputStream fis = new FileInputStream(file)) {
            while ((len = fis.read(buffer)) > 0) {
                zos.write(buffer, 0, len);
                zos.flush();
            }
            zos.closeEntry();
        } catch (IOException e) {
            System.out.println("====压缩单个文件异常====" + e);
        }
    }

    //生成随机数
    public static String dateRandom18() {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
        String date = simpleDateFormat.format(new Date());
        String timeMillis = String.valueOf(System.currentTimeMillis());
        String fiveNumber = timeMillis.substring(timeMillis.length() - 6);
        String tempRandom = String.valueOf(Math.random());
        String number = tempRandom.substring(tempRandom.length() - 4);
        return date + fiveNumber + number;
    }

    //测试方法
    public static void main(String[] args) {

        String zipPathDir = "D:/";
        String zipFileName = "测试文件.zip";
        List<String> list = new ArrayList<>();
        list.add("D:/a.txt");
        list.add("D:/b.txt");

        compressFiles(zipPathDir, zipFileName, list);
    }
}

