package com.xiaoniu.subsystem.strategy;

import cn.hutool.core.io.FastByteArrayOutputStream;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.xiaoniu.subsystem.strategy.bean.FileObj;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.archivers.sevenz.SevenZArchiveEntry;
import org.apache.commons.compress.archivers.sevenz.SevenZFile;
import org.apache.commons.compress.utils.SeekableInMemoryByteChannel;

import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

@Slf4j
public class SevenZAnalysisStrategy implements UnZipStrategy {
    @Override
    public List<FileObj> analysis(InputStream inputStream) {
        List<FileObj> list = new ArrayList<>();
        FastByteArrayOutputStream read = IoUtil.read(inputStream);
        byte[] byteArray = read.toByteArray();
        SeekableInMemoryByteChannel seekableInMemoryByteChannel = new SeekableInMemoryByteChannel(byteArray);
        try {
            SevenZFile sevenZFile = new SevenZFile(seekableInMemoryByteChannel);
            // 创建输出目录
            SevenZArchiveEntry entry;
            while ((entry = sevenZFile.getNextEntry()) != null) {
                if (!entry.isDirectory()) {
                    String name = entry.getName();
                    log.info("解析文件：{}", name);
                    FileObj fileObj = new FileObj();
                    fileObj.setDocType(1);
                    fileObj.setFilePath(name);
                    //后缀
                    //先判断name中是否包含/（路径分隔符）
                    int index2 = name.lastIndexOf("/");
                    if(index2==-1){
                        int index = name.lastIndexOf(".");
                        if (index!=-1) {
                            String suffix = name.substring(index + 1);
                            fileObj.setSuffix(suffix);
                        }
                    }else {
                        //截取最后的/到最后一个字符
                        String sub = name.substring(name.lastIndexOf("/"));
                        int index = sub.lastIndexOf(".");
                        if (index!=-1) {
                            String suffix = sub.substring(index + 1);
                            fileObj.setSuffix(suffix);
                        }
                    }
                    log.info("suffix:{}", fileObj.getSuffix());
                    //原文档名称
                    int index1 = name.lastIndexOf("/");
                    String docName = name.substring(index1 + 1);
                    log.info("docName:{}", docName);
                    fileObj.setDocName(docName);
                    //上传后的文件名字
                    String uuid = IdUtil.fastSimpleUUID();
                    StringBuilder fileName=new StringBuilder(uuid);
                    if (StrUtil.isNotBlank(fileObj.getSuffix())) {
                        fileName.append(".").append(fileObj.getSuffix());
                    }
                    fileObj.setFileName(fileName.toString());
                    log.info("fileName:{}",fileName);
                    //解压到本地临时存储路径
                    /*StringBuilder localPath=new StringBuilder();
                    String userDir = System.getProperty("user.dir");
                    localPath.append(userDir).append("/").append(fileObj.getFileName());
                    fileObj.setLocalPath(localPath.toString());
                    log.info("解压文件在本地临时路径：{}",localPath);
                    FileOutputStream fileOutputStream = new FileOutputStream(localPath.toString());
                    int len = 0;
                    byte[] b = new byte[2048];
                    while ((len = sevenZFile.read(b)) != -1) {
                        fileOutputStream.write(b, 0, len);
                    }
                    fileOutputStream.close();*/
                    // 使用 ByteArrayOutputStream 来存储字节数据
                    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                    byte[] buffer = new byte[1024];
                    int length;

                    // 从 ArchiveInputStream 读取数据并写入 ByteArrayOutputStream
                    while ((length = sevenZFile.read(buffer)) > 0) {
                        byteArrayOutputStream.write(buffer, 0, length);
                    }

                    // 返回字节数组
                    byte[] fileData = byteArrayOutputStream.toByteArray();
                    fileObj.setBytes(fileData);
                    byteArrayOutputStream.close();
                    list.add(fileObj);
                }
            }
            inputStream.close();
            read.close();
            seekableInMemoryByteChannel.close();
            log.info("完成解压文件");
        } catch (IOException e) {
            log.error("7z格式的压缩文件在解压时发生错误：", e);
            throw new RuntimeException(e);
        }
        return list;
    }
}
