package com.xiaoniu.subsystem.strategy.callback;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.xiaoniu.subsystem.strategy.bean.FileObj;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import net.sf.sevenzipjbinding.*;

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

@Slf4j
public class RarExtractCallback implements IArchiveExtractCallback {

    private Integer index;
    private IInArchive inArchive;
    private ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

    @Getter
    private List<FileObj> fileObjs = new ArrayList<>();

    public RarExtractCallback(IInArchive inArchive) {
        this.inArchive = inArchive;
    }


    @Override
    public void setCompleted(long arg0) throws SevenZipException {

    }

    @Override
    public void setTotal(long arg0) throws SevenZipException {
    }

    @Override
    public ISequentialOutStream getStream(int index, ExtractAskMode extractAskMode) throws SevenZipException {
        this.index = index;
        boolean isFolder = (boolean) inArchive.getProperty(index, PropID.IS_FOLDER);
        return data -> {
            if (!isFolder) {
                try {
                    outputStream.write(data);
                } catch (IOException e) {
                    log.error("rar格式的压缩文件在解压时发生错误：", e);
                    throw new RuntimeException(e);
                }
            }
            return data.length;
        };
    }

    @Override
    public void prepareOperation(ExtractAskMode arg0) throws SevenZipException {
    }

    @Override
    public void setOperationResult(ExtractOperationResult extractOperationResult) throws SevenZipException {
        String name = (String) inArchive.getProperty(index, PropID.PATH);
        boolean isFolder = (boolean) inArchive.getProperty(index, PropID.IS_FOLDER);
        if (!isFolder) {
            name = name.replace("\\", "/");
            log.info("解析文件：{}", name);
            FileObj fileObj = new FileObj();
            fileObj.setDocType(1);
            fileObj.setFilePath(name);
            //后缀
            int index = name.lastIndexOf(".");
            if (index != -1) {
                String suffix = name.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());
            //解压到本地临时存储路径
            StringBuilder localPath = new StringBuilder();
            String userDir = System.getProperty("user.dir");
            localPath.append(userDir).append("/").append(fileObj.getFileName());
            fileObj.setLocalPath(localPath.toString());
            log.info("解压文件在本地临时路径：{}", localPath);
            try {
                byte[] byteArray = outputStream.toByteArray();
                fileObj.setBytes(byteArray);
              /*  FileOutputStream fileOutputStream = new FileOutputStream(localPath.toString());
                fileOutputStream.write(byteArray);
                outputStream.reset();
                fileOutputStream.close();*/
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            log.info("完成解压文件");
            fileObjs.add(fileObj);
        }
    }
}


