package com.engine.custom.hg.util;

import km.org.apache.poi.util.TempFile;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;
import org.apache.tools.zip.ZipOutputStream;
import weaver.general.BaseBean;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;


public class ZipUtil {
    static final int BUFFER = 2048;


    //创建文件夹
    public File crFile(String pathName){
        // bean.writeLog("创建文件夹==="+pathName);
        File file=new File(pathName);
        try {
            // bean.writeLog("创建文件夹==="+file.exists());
            if(!file.exists()){
                file.mkdir();
            }
        }catch (Exception E){
            // bean.writeLog("Exception"+E.getMessage());
        }
        return file;
    }

    public String mkTemper(String filePath){
        crFile(filePath);
        Date date = new Date();
        SimpleDateFormat ft = new SimpleDateFormat ("yyyyMMdd");
        crFile(filePath+"/"+ft.format(date));
        return filePath+"/"+ft.format(date);
    }

    public void writeToTxt(String path,String title,String content,Boolean append){
        try {
            /* 写入Txt文件 */
            File mkdirsName = new File(path);
            // 相对路径
            if(!mkdirsName.exists()){
                mkdirsName.mkdirs();
            }
            File writename = new File(path+"/"+title+".txt");
            // 存在即根据操作系统添加换行符
            if(!writename.exists() && append==true) {
                // 创建新文件
                writename.createNewFile();
            }else if("del".equals(content) && append==false){
                writename.delete();
                return;
            }else if(!writename.exists() && append==false){
                writename.createNewFile();
            }else {
                String osName = System.getProperties().getProperty("os.name");
                System.out.println(osName);
                if ("Linux".equals(osName)) {
                    content = "\r" + content;
                } else {
                    content = "\r\n" + content;
                }
            }
            // 如果是在原有基础上写入则append属性为true，默认为false
            BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(writename, append), StandardCharsets.UTF_8));
            // 写入TXT
            out.write(content);
            // 把缓存区内容压入文件
            out.flush();
            // 最后记得关闭文件
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // /**
    //  *
    //  * @param ZIP_FILE_AFTER 压缩文件
    //  * @param ZIP_FILE_BEFORE 解压地址
    //  * @param fileName 重命名
    //  * @return
    //  */
    // public static boolean zipToFolder(String ZIP_FILE_AFTER, String ZIP_FILE_BEFORE ,String fileName) {
    //     try {
    //         BaseBean bean =  new BaseBean();
    //         ZipFile zipFile = new ZipFile(ZIP_FILE_AFTER);
    //         Enumeration emu = zipFile.entries();
    //         // bean.writeLog(ZIP_FILE_AFTER+"=="+ZIP_FILE_BEFORE+"=="+fileName);
    //         int i = 0;
    //         while (emu.hasMoreElements()) {
    //             ZipEntry entry = (ZipEntry) emu.nextElement();
    //             // bean.writeLog("entry.getName()"+entry.getName());
    //             // 会把目录作为一个file读出一次，所以只建立目录就可以，之下的文件还会被迭代到。
    //
    //             if (entry.isDirectory()) {
    //                 new File(ZIP_FILE_BEFORE + File.separator+new String(entry.getName().getBytes(StandardCharsets.UTF_8))).mkdirs();
    //                 continue;
    //             }
    //
    //             BufferedInputStream bis = new BufferedInputStream(zipFile
    //                     .getInputStream(entry));
    //             InputStreamReader isr = new InputStreamReader(bis);
    //             // File file = new File(ZIP_FILE_BEFORE +File.separator+ entry.getName());
    //             String s = new String(entry.getName().getBytes(StandardCharsets.UTF_8));
    //             File file = new File(ZIP_FILE_BEFORE + File.separator + s );
    //             bean.writeLog("entry.getName()==="+s);
    //             // 加入这个的原因是zipfile读取文件是随机读取的，这就造成可能先读取一个文件
    //             // 而这个文件所在的目录还没有出现过，所以要建出目录来。
    //             File parent = file.getParentFile();
    //             if (parent != null && (!parent.exists())) {
    //                 parent.mkdirs();
    //             }
    //
    //             FileOutputStream fos = new FileOutputStream(file);
    //             BufferedOutputStream bos = new BufferedOutputStream(fos, BUFFER);
    //             OutputStreamWriter osw = new OutputStreamWriter(bos);
    //
    //             int count;
    //             char data[] = new char[BUFFER];
    //
    //             while ((count = isr.read(data, 0, BUFFER)) != -1) {
    //                 osw.write(data, 0, count);
    //             }
    //             bos.flush();
    //             bos.close();
    //             isr.close();
    //         }
    //         zipFile.close();
    //         System.out.println(1);
    //     } catch (Exception e) {
    //         e.printStackTrace();
    //         System.out.println(0);
    //         return false;
    //     }
    //     return true;
    // }




    public static void addFolderToZip(String folderPath, ZipOutputStream zos, String baseFolderPath) throws IOException {
        File folder = new File(folderPath);
        File[] files = folder.listFiles();

        for (File file : files) {
            if (file.isDirectory()) {
                addFolderToZip(file.getAbsolutePath(), zos, baseFolderPath);
            } else {
                String entryName = file.getAbsolutePath().replace(baseFolderPath, "");
                entryName = entryName.startsWith(File.separator) ? entryName.substring(1) : entryName;

                ZipEntry zipEntry = new ZipEntry(entryName);
                zos.putNextEntry(zipEntry);

                FileInputStream fis = new FileInputStream(file);
                byte[] buffer = new byte[1024];
                int length;
                while ((length = fis.read(buffer)) > 0) {
                    zos.write(buffer, 0, length);
                }

                fis.close();
                zos.closeEntry();
            }
        }


    }


    public static void addInputStreamToZip(InputStream inputStream, ZipOutputStream zos, String entryName) throws IOException {

        ZipEntry zipEntry = new ZipEntry(entryName);
        zos.putNextEntry(zipEntry);
        byte[] buffer = new byte[1024];
        int length;
        while ((length = inputStream.read(buffer)) > 0) {
            zos.write(buffer, 0, length);
        }
        inputStream.close();
        zos.closeEntry();
    }

    public static   void filesToZip(File srcFile , OutputStream out , String fileName)throws RuntimeException {

        long start = System.currentTimeMillis();
        ZipOutputStream zos = null ;
        try {
            zos = new ZipOutputStream(out);

            byte[] buf = new byte[BUFFER];
            zos.putNextEntry(new ZipEntry(fileName));
            int len;
            FileInputStream in = new FileInputStream(srcFile);
            while ((len = in.read(buf)) != -1){
                zos.write(buf, 0, len);
            }
            zos.closeEntry();
            in.close();

            long end = System.currentTimeMillis();
        } catch (Exception e) {
            throw new RuntimeException("zip error from ZipUtils",e);
        }finally{
            if(zos != null){
                try {
                    zos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
