package nckd.base.helper;

import kd.bos.fileservice.extension.PreviewExt;
import kd.bos.logging.Log;
import kd.bos.logging.LogFactory;
import org.springframework.util.StreamUtils;

import java.io.IOException;
import java.io.InputStream;

/**
 * 预览解密扩展类
 * @author wanghaiwu_kd
 * @date 2025/06/26
 */
public class CustomPreviewExtension implements PreviewExt {
    private static final Log logger = LogFactory.getLog(CustomPreviewExtension.class);

    @Override
    public InputStream beforePreviewTempFile(String tempFileUrl, InputStream in) {
        // 临时⽂件预览
        // 对 原始⽂件流 in 进⾏处理，原始⽂件流使⽤后需关闭。
        logger.info("--------------beforePreviewTempFile 解密 开始");

        InputStream decodedIn = FileSECUtils.processFileWithSEC(tempFileUrl, in);

        logger.info("--------------beforePreviewTempFile 解密 结束");

        return decodedIn; // 返回处理后的⽂件流
    }

    @Override
    public InputStream beforePreviewFile(String originPath, InputStream in) {
        // 持久化⽂件预览
        // 对原始⽂件流 in 进⾏处理，原始⽂件流使⽤后需关闭。
        logger.info("--------------beforePreviewFile 解密 开始");

        InputStream decodedIn = FileSECUtils.processFileWithSEC(originPath, in);

        try {
            if (in != null) {
                in.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
            logger.info("--------------beforePreviewFile 关闭流: " + e.getMessage());
        }

        logger.info("--------------beforePreviewFile 解密 结束");

        return decodedIn; // 返回处理后的⽂件流
    }
}
