package org.dromara.settlement.common.file;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;

/**
 * 压缩(实现的Zip)工具
 */
public class ZipUtils {

	/********************************** 压缩start ***************************************/
	/**
	 * 压缩文件-由于out要在递归调用外,所以封装一个方法用来 调用ZipFiles(ZipOutputStream out,String
	 * path,File... srcFiles)
	 *
	 * @param zip
	 * @param path
	 * @param srcFiles
	 * @throws IOException
	 */
	public static void zipFiles(File zip, File... srcFiles) throws IOException {
		String path = "";
		ZipOutputStream out = null;
		try {
			out = new ZipOutputStream(new FileOutputStream(zip));
			ZipFiles(out, path, srcFiles);
		} catch (Exception e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		} finally {
			if (out != null)
				out.close();
		}
		System.out.println("*****************压缩完毕*******************");
	}

	public static void zipFiles(String zip, List<String> srcFilePaths)
			throws IOException {
		File zipFile = new File(zip);
		File[] srcFiles = new File[srcFilePaths.size()];
		for (int i = 0, len = srcFilePaths.size(); i < len; i++) {
			srcFiles[i] = new File(srcFilePaths.get(i));
		}
		zipFiles(zipFile, srcFiles);
	}

	/**
	 * 压缩文件-File
	 *
	 * @param zipFile
	 *            zip文件
	 * @param srcFiles
	 *            被压缩源文件
	 */
	private static void ZipFiles(ZipOutputStream out, String path,
			File... srcFiles) {
		path = path.replaceAll("\\*", "/");
		if (!path.endsWith("/")) {
			path += "/";
		}
		byte[] buf = new byte[1024];
		FileInputStream in = null;
		try {
			for (File srcFile : srcFiles) {
				if (srcFile.isDirectory()) {
					File[] files = srcFile.listFiles();
					out.putNextEntry(new ZipEntry(path));
					ZipFiles(out, path, files);
				} else {
					in = new FileInputStream(srcFile);
					System.out.println(path + srcFile.getName());
					out.putNextEntry(new ZipEntry(path + srcFile.getName()));
					int len;
					while ((len = in.read(buf)) > 0) {
						out.write(buf, 0, len);
					}
					out.closeEntry();
					in.close();
					in = null;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
					// TODO 自动生成的 catch 块
					e.printStackTrace();
				}
			}
		}
	}

	/********************************** 压缩end ***************************************/

	/********************************** 解压缩start ***************************************/
	/**
	 * 解压到指定目录
	 *
	 * @param zipPath
	 * @param descDir
	 */
	public static void unZipFiles(String zipPath, String descDir)
			throws IOException {
		unZipFiles(new File(zipPath), descDir);
	}

	/**
	 * 解压文件到指定目录
	 *
	 * @param zipFile
	 * @param descDir
	 */
	private static void unZipFiles(File zipFile, String descDir)
			throws IOException {
		File pathFile = new File(descDir);
		if (!pathFile.exists()) {
			pathFile.mkdirs();
		}
		ZipFile zip = new ZipFile(zipFile);
		for (Enumeration entries = zip.entries(); entries.hasMoreElements();) {
			ZipEntry entry = (ZipEntry) entries.nextElement();
			String zipEntryName = entry.getName();
			InputStream in = zip.getInputStream(entry);
			String outPath = (descDir + zipEntryName).replaceAll("\\*", "/");
			;
			// 判断路径是否存在,不存在则创建文件路径
			File file = new File(outPath.substring(0, outPath.lastIndexOf('/')));
			if (!file.exists()) {
				file.mkdirs();
			}
			// 判断文件全路径是否为文件夹,如果是上面已经上传,不需要解压
			if (new File(outPath).isDirectory()) {
				continue;
			}
			// 输出文件路径信息
			System.out.println(outPath);

			OutputStream out = new FileOutputStream(outPath);
			byte[] buf1 = new byte[1024];
			int len;
			while ((len = in.read(buf1)) > 0) {
				out.write(buf1, 0, len);
			}
			in.close();
			out.close();
		}
		zip.close();
		System.out.println("******************解压完毕********************");
	}

	/********************************** 解压缩end ***************************************/

	/**
	 * 解压缩一个文件
	 *
	 * @param zipFile
	 *            压缩文件
	 * @param folderPath
	 *            解压缩的目标目录
	 * @throws IOException
	 *             当解压缩过程出错时抛出
	 */
	public static void upZipFile(File zipFile, String folderPath)
			throws ZipException, IOException {
		File desDir = new File(folderPath);
		if (!desDir.exists()) {
			desDir.mkdirs();
		}
		ZipFile zf = new ZipFile(zipFile);
		for (Enumeration<?> entries = zf.entries(); entries.hasMoreElements();) {
			ZipEntry entry = ((ZipEntry) entries.nextElement());
			InputStream in = zf.getInputStream(entry);
			String str = folderPath + File.separator + entry.getName();
			str = new String(str.getBytes("8859_1"), "GB2312");
			File desFile = new File(str);
			if (!desFile.exists()) {
				File fileParentDir = desFile.getParentFile();
				if (!fileParentDir.exists()) {
					fileParentDir.mkdirs();
				}
				desFile.createNewFile();
			}
			OutputStream out = new FileOutputStream(desFile);
			byte buffer[] = new byte[1024 * 1024];
			int realLength;
			while ((realLength = in.read(buffer)) > 0) {
				out.write(buffer, 0, realLength);
			}
			out.close();
			in.close();
		}
		zf.close();
	}

	/** 第一个参数是压缩文件路径，第二个参数是要解压的文件夹路径，文件夹可以不存在会自动生成 */
	public static void ZipDecompress(String frompath, String topath)
			throws IOException {
		ZipFile zf = new ZipFile(new File(frompath));
		InputStream inputStream;
		Enumeration en = zf.entries();
		while (en.hasMoreElements()) {
			ZipEntry zn = (ZipEntry) en.nextElement();
			if (!zn.isDirectory()) {
				inputStream = zf.getInputStream(zn);
				File f = new File(topath + zn.getName());
				File file = f.getParentFile();
				file.mkdirs();
				System.out.println(zn.getName() + "---" + zn.getSize());

				FileOutputStream outputStream = new FileOutputStream(topath
						+ File.separator + zn.getName());
				int len = 0;
				byte bufer[] = new byte[1024];
				while (-1 != (len = inputStream.read(bufer))) {
					outputStream.write(bufer, 0, len);
				}
				outputStream.close();
			}
		}
		zf.close();
	}

	/**
	 * 解压文件名包含传入文字的文件
	 *
	 * @param zipFile
	 *            压缩文件
	 * @param folderPath
	 *            目标文件夹
	 * @param nameContains
	 *            传入的文件匹配名
	 * @throws ZipException
	 *             压缩格式有误时抛出
	 * @throws IOException
	 *             IO错误时抛出
	 */
	public static ArrayList<File> upZipSelectedFile(File zipFile,
			String folderPath, String nameContains) throws ZipException,
			IOException {
		ArrayList<File> fileList = new ArrayList<File>();

		File desDir = new File(folderPath);
		if (!desDir.exists()) {
			desDir.mkdir();
		}

		ZipFile zf = new ZipFile(zipFile);
		for (Enumeration<?> entries = zf.entries(); entries.hasMoreElements();) {
			ZipEntry entry = ((ZipEntry) entries.nextElement());
			if (entry.getName().contains(nameContains)) {
				InputStream in = zf.getInputStream(entry);
				String str = folderPath + File.separator + entry.getName();
				str = new String(str.getBytes("8859_1"), "GB2312");
				// str.getBytes("GB2312"),"8859_1" 输出
				// str.getBytes("8859_1"),"GB2312" 输入
				File desFile = new File(str);
				if (!desFile.exists()) {
					File fileParentDir = desFile.getParentFile();
					if (!fileParentDir.exists()) {
						fileParentDir.mkdirs();
					}
					desFile.createNewFile();
				}
				OutputStream out = new FileOutputStream(desFile);
				byte buffer[] = new byte[1024 * 1024];
				int realLength;
				while ((realLength = in.read(buffer)) > 0) {
					out.write(buffer, 0, realLength);
				}
				in.close();
				out.close();
				fileList.add(desFile);
			}
		}
		return fileList;
	}
}
