package cn.edu.whu.boot.common.utils.collection;

import cn.edu.whu.boot.common.domain.CommonConstant;
import net.lingala.zip4j.core.ZipFile;
import net.lingala.zip4j.exception.ZipException;
import net.lingala.zip4j.model.ZipParameters;
import net.lingala.zip4j.util.Zip4jConstants;
import org.apache.commons.io.FileUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * 将多媒体数据存储到本地的工具类，另外还涉及压缩解压的方法
 */
public class StoreMediaFileUtil{

    /**
     * 将安卓端传来的多媒体信息压缩包储存在指定在路径中
     *
     * @param file 多媒体文件压缩包
     * @param path 储存路径
     */
    public static String storeFileAndUnzip(MultipartFile file, String path){
        String unZipPath;
        if(file != null && file.isEmpty()){
            System.out.println(" --- 未接收到文件! --- ");
        }
        else{
            File folder = new File(path);
            folder.mkdirs();
            File zipFile = new File(path + File.separator + file.getOriginalFilename());
            try{
                zipFile.createNewFile();
                file.transferTo(zipFile);
                unZipPath = zipFile.getAbsolutePath().substring(0, zipFile.getAbsolutePath().lastIndexOf(File.separator));
                unZip(zipFile.getAbsolutePath(), unZipPath, null);
                zipFile.delete();
                File zipDir = new File(path + File.separator + file.getOriginalFilename().substring(0, file.getOriginalFilename().indexOf('.')));
                if(zipDir.exists() && zipDir.isDirectory()){
                    FileUtils.deleteDirectory(zipDir);
                }
            } catch(ZipException e){
                e.printStackTrace();
                return CommonConstant.FAILED;
            } catch(java.util.zip.ZipException e){
                System.out.println("解压失败");
                return CommonConstant.FAILED;
            } catch(IOException e){
                e.printStackTrace();
                System.out.println("文件上传失败");
                return CommonConstant.FAILED;
            }
        }
        return CommonConstant.SUCCEED;
    }

    /**
     * 解压加密的压缩文件
     *
     * @param zipfile 待解压文件
     * @param dest 解压路径
     * @param passwd 解压密码
     */
    public static void unZip(String zipfile, String dest, String passwd) throws ZipException{
        ZipFile zfile = new ZipFile(zipfile);
        if(!zfile.isValidZipFile()){
            throw new ZipException("压缩文件不合法，可能已经损坏！");
        }
        File destFile = new File(dest);
        if(destFile.isDirectory() && !destFile.exists()){
            destFile.mkdirs();
        }
        if(zfile.isEncrypted()){
            zfile.setPassword(passwd.toCharArray());
        }
        zfile.extractAll(dest);
    }

    /**
     * 压缩文件
     *
     * @param mediaPath 中间压缩包的暂存路径
     * @param filePathList 待压缩文件List
     * @param password 压缩密码
     * @return 返回压缩文件的filePath，便于上传后删除
     */
//    public static String zip(String mediaPath, List<String> filePathList, String password){
//        String destFileName = mediaPath + "/temp.zip";
//        ZipParameters zipParam = new ZipParameters();
//        zipParam.setCompressionMethod(Zip4jConstants.COMP_DEFLATE);
//        zipParam.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL);
//        if(password != null){
//            zipParam.setEncryptFiles(true);
//            zipParam.setEncryptionMethod(Zip4jConstants.ENC_METHOD_STANDARD);
//            zipParam.setPassword(password.toCharArray());
//        }
//        try{
//            ZipFile zipfile = new ZipFile(destFileName);
//            for(String filePath : filePathList){
//                File srcFile = new File(filePath.contains(CommonConstant.STATIC_RESOURCE_ROOT) ? filePath : mediaPath + filePath);
//                if(srcFile.isDirectory()){
//                    File[] filesList = srcFile.listFiles();
//                    for(File file : filesList){
//                        if(file.isDirectory()){
//                            zipfile.addFolder(srcFile, zipParam);
//                        }
//                        else{
//                            zipfile.addFile(file, zipParam);
//                        }
//                    }
//                }
//                else{
//                    zipfile.addFile(srcFile, zipParam);
//                }
//            }
//        } catch(ZipException e){
//            e.printStackTrace();
//        }
//        return destFileName;
//    }
    public static String zip(String mediaPath, List<String> filePathList, String password) {
        String destFileName = mediaPath + "/temp.zip";
        ZipParameters zipParam = new ZipParameters();
        zipParam.setCompressionMethod(Zip4jConstants.COMP_DEFLATE);
        zipParam.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL);

        if (password != null && !password.isEmpty()) {
            zipParam.setEncryptFiles(true);
            zipParam.setEncryptionMethod(Zip4jConstants.ENC_METHOD_STANDARD);
            zipParam.setPassword(password.toCharArray());
        }

        try {
            ZipFile zipfile = new ZipFile(destFileName);

            for (String filePath : filePathList) {
                File srcFile = new File(filePath.contains(CommonConstant.STATIC_RESOURCE_ROOT) ? filePath : mediaPath + filePath);
                //File srcFile = new File(filePath);
                if (!srcFile.exists()) {
                    System.err.println("⚠️ 文件或目录不存在，跳过：" + srcFile.getAbsolutePath());
                    continue;
                }

                if (srcFile.isDirectory()) {
                    zipfile.addFolder(srcFile, zipParam);
                } else {
                    zipfile.addFile(srcFile, zipParam);
                }
            }
        } catch (ZipException e) {
            e.printStackTrace();
            throw new RuntimeException("压缩失败：" + e.getMessage(), e);
        }

        return destFileName;
    }

}
