package com.xiaoniu.subsystem.strategy;

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.ArchiveEntry;
import org.apache.commons.compress.archivers.ArchiveInputStream;
import org.apache.commons.compress.archivers.zip.ZipArchiveInputStream;

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

@Slf4j
public class ZipAnalysisStrategy implements UnZipStrategy {

    @Override
    public List<FileObj> analysis(InputStream inputStream) {
        List<FileObj> list = new ArrayList<>();
        ArchiveInputStream ais = new ZipArchiveInputStream(inputStream, "GBK");
        ArchiveEntry entry;
        try {
            while ((entry = ais.getNextEntry()) != null) {
                if (!entry.isDirectory()) {
                    FileObj fileObj = extractFile(ais, entry);
                    list.add(fileObj);
                }
            }
            ais.close();
            inputStream.close();
        } catch (IOException e) {
            log.error("zip格式压缩文件在解压时发生错误：", e);
            throw new RuntimeException(e);
        }
        log.info("完成解压文件");
        return list;
    }

    private FileObj extractFile(ArchiveInputStream ais, ArchiveEntry entry) throws IOException {
        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());
        byte[] buffer = new byte[1024];
        int length;
        while ((length = ais.read(buffer)) > 0) {
            fileOutputStream.write(buffer, 0, length);
        }
        fileOutputStream.close();*/
        // 使用 ByteArrayOutputStream 来存储字节数据
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int length;

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

        // 返回字节数组
        byte[] fileData = byteArrayOutputStream.toByteArray();
        byteArrayOutputStream.close();
        fileObj.setBytes(fileData);
        return fileObj;
    }

}
