package com.tofly.feesapi.common.dzht;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Component;

import java.io.*;

@Component
public class SpringUtils implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        if (SpringUtils.applicationContext == null) {
            SpringUtils.applicationContext = applicationContext;
        }
    }

    public static Object getBean(String name) {
        return applicationContext.getBean(name);
    }

    public static <T> T getBean(Class<T> requiredType) {
        return applicationContext.getBean(requiredType);
    }

    public static InputStream readResourceFile(String path) throws IOException {
        Resource resource = applicationContext.getResource(path);
        InputStream inputStream = resource.getInputStream();
        return inputStream;
    }

    public static File getResourceFile(String path) throws IOException {
        Resource resource = applicationContext.getResource(path);
        return resource.getFile();
    }

    /**
     * 将 InputStream 转换为 FileInputStream
     */
    public static FileInputStream convertInputStreamToFileInputStream(InputStream inputStream) throws IOException {
        // 从 inputStream 创建一个临时文件
        File tempFile = File.createTempFile("temp", ".tmp");
        tempFile.deleteOnExit(); // 确保程序退出时删除临时文件

        // 将 inputStream 写入临时文件
        try (FileOutputStream out = new FileOutputStream(tempFile)) {
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                out.write(buffer, 0, bytesRead);
            }
        }

        // 返回新的 FileInputStream 对象，从临时文件中读取数据
        return new FileInputStream(tempFile);
    }
}