package org.springblade.modules.appmenu.util;

import net.lingala.zip4j.model.FileHeader;
import net.lingala.zip4j.model.ZipParameters;
import net.lingala.zip4j.util.Zip4jConstants;
import org.apache.http.util.TextUtils;
import org.springblade.core.tool.utils.StringUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.zip.ZipException;

public class ZipUtils {
	/**
	 * 分卷压缩
	 * @param srcFiles 要压缩的文件绝对路径列表（支持多个文件的合并压缩）
	 * @param destFile 要压缩的zip文件名
	 * @param passwd   压缩密码
	 * @param fileSize 分卷大小
	 * @return 压缩文件路径（如分卷会返回以 "," 分隔的文件路径列表）
	 * @throws ZipException
	 */
	public static String zip(List<String> srcFiles, String destFile, String passwd, long fileSize) throws ZipException, net.lingala.zip4j.exception.ZipException {
		String zipFiles = null;
		File tmpFile = new File(destFile);
		if(tmpFile.exists()){
			tmpFile.delete();
		}

		net.lingala.zip4j.core.ZipFile zipFile = new net.lingala.zip4j.core.ZipFile(destFile);

		ArrayList<File> filesToAdd = new ArrayList<File>();
		if(srcFiles!=null&&srcFiles.size()>0){

			int fileCount = srcFiles.size();
			for(int i=0;i<fileCount;i++){
				filesToAdd.add(new File(srcFiles.get(i)));
			}

			ZipParameters parameters = new ZipParameters();
			if(!StringUtil.isBlank(passwd)) {
				parameters.setEncryptFiles(true);
				parameters.setEncryptionMethod(Zip4jConstants.ENC_METHOD_STANDARD);
				parameters.setPassword(passwd.toCharArray());
			}
			parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE);

			parameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL);

			//未指定则设置为512KB
			if(fileSize==0){
				fileSize = 65536;
			}
			zipFile.createZipFile(filesToAdd, parameters, true, fileSize);

			ArrayList<String> zipList = zipFile.getSplitZipFiles();
			if(zipList!=null&&zipList.size()>0){
				String surFix = ".z010";
				String surFixReplace = ".z10";
				for(int i=0;i<zipList.size();i++){//针对第10个包的文件名做特殊处理
					String file = zipList.get(i).trim();
					int length = file.length();
					String surFixTmp = file.substring(length-5, length);
					if(surFix.equals(surFixTmp)){
						file = file.replace(surFix, surFixReplace);
					}
					zipList.set(i, file);
				}
				String[] zipArray = new String[zipList.size()];
				zipList.toArray(zipArray);
				zipFiles = Arrays.toString(zipArray);

				int length = zipFiles.length();
				zipFiles = zipFiles.substring(1, length - 1);
			}
		}
		return zipFiles;
	}


	public static void main(String[] args) throws ZipException, net.lingala.zip4j.exception.ZipException {
//		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
//		String format = simpleDateFormat.format(new Date());
//		System.out.println(format);
//
//		//带压缩文件集合
//		List<String> srcFiles = new ArrayList<String>();
//		srcFiles.add("C:\\Users\\ASUS\\Desktop\\微信支付\\uaac.apk");
//		String destFile = "C:\\Users\\ASUS\\Desktop\\微信支付\\"+format+"uaac"+".apk"; //压缩路径
//
//		String passwd  = null; //压缩包密码
//		long fileSize = 7 * 1024 * 1024; //分卷大小（当前为最小值）
//
//		try {
//			//1.压缩
//			try {
//				System.out.println(zip(srcFiles,destFile,passwd,fileSize));
//			} catch (net.lingala.zip4j.exception.ZipException e) {
//				e.printStackTrace();
//			}
//
//			//2.解压
////            String[] extractedFiles=unzip(destFile, "C:/test/a", passwd);
////            for (int i = 0; i < extractedFiles.length; i++) {
////                System.out.println(extractedFiles[i]);
////            }
//
//		} catch (ZipException e) {
//			e.printStackTrace();
//		}
		String destFile = "C:\\Users\\ASUS\\Desktop\\www\\20221206160934_unappstore_com.zip"; //压缩路径
		unzip(destFile,"C:\\Users\\ASUS\\Desktop\\新建文件夹 (7)","");

	}


	public static String[] unzip(String zipFilePath, String dest, String passwd) throws ZipException, net.lingala.zip4j.exception.ZipException {
		File zipFile = new File(zipFilePath);
		net.lingala.zip4j.core.ZipFile zFile = new net.lingala.zip4j.core.ZipFile(zipFile);
		zFile.setFileNameCharset("GBK");
		if(!zFile.isValidZipFile()) {
			throw new ZipException("压缩文件不合法,可能被损坏!");
		}

		File destDir = new File(dest);
		if(destDir.isDirectory() && !destDir.exists()) {
			destDir.mkdir();
		}

		if(zFile.isEncrypted()) {
			if(TextUtils.isEmpty(passwd)) {
				throw new ZipException("文件已加密，需要解压密码，解压密码不能为空！");
			}else {
				zFile.setPassword(passwd.toCharArray());
			}
		}
		zFile.extractAll(dest);

		List<String> extractedFileList = new ArrayList<String>();

		List<FileHeader> headerList = zFile.getFileHeaders();
		if(headerList!=null&&headerList.size()>0) {
			for(FileHeader fileHeader:headerList) {
				if(!fileHeader.isDirectory()) {
					extractedFileList.add(fileHeader.getFileName());
				}
			}
		}

		String[] extractedFiles = new String[extractedFileList.size()];
		extractedFileList.toArray(extractedFiles);
		return extractedFiles;
	}
}
