package com.emoon.knowledge.service.impl;

import com.emoon.knowledge.chain.loader.ResourceLoader;
import com.emoon.knowledge.chain.loader.ResourceLoaderFactory;
import com.emoon.knowledge.service.IFileParseService;
import jakarta.annotation.Resource;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;


import java.io.InputStream;


@Slf4j
@Service
@RequiredArgsConstructor
public class FileParseServiceImpl implements IFileParseService{

    @Resource
    private ResourceLoaderFactory resourceLoaderFactory;

    /**
     * 根据文件类型解析文件内容
     */
    @Override
    public String parseFileContent(MultipartFile file) {
        if (file == null || file.isEmpty()) {
            throw new RuntimeException("文件不能为空");
        }

        String fileName = file.getOriginalFilename();
        if (fileName == null) {
            throw new RuntimeException("文件名为空");
        }

        // 获取文件后缀
        String fileType = fileName.substring(fileName.lastIndexOf(".") + 1);

        try (InputStream inputStream = file.getInputStream()) {
            // 根据文件类型选择对应的 loader
            ResourceLoader loader = resourceLoaderFactory.getLoaderByFileType(fileType);
            // 解析原文
            return loader.getContent(inputStream);
        } catch (Exception e) {
            throw new RuntimeException("文件解析失败: " + e.getMessage(), e);
        }
    }

}
