package com.ruoyi.ibs.dashboard.service;

import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.List;

/**
 * @Author 吴凯程
 * @Date 2025/5/19
 **/
@Slf4j
@Service
public class FileOptService {

    public String getFileSeparator() {
        String os = System.getProperty("os.name").toLowerCase();
        if (os.contains("win")) {
            return "\\";
        } else {
            return "/";
        }
    }


    public String saveFile(MultipartFile file) throws Exception {
        String filePath = RuoYiConfig.getFileRootPath();
        String fileName = FileUploadUtils.extractFilename(file);
        String absPath = FileUploadUtils.getAbsoluteFile(filePath, fileName).getAbsolutePath();
        file.transferTo(Paths.get(absPath));
        log.info("文件保存路径：{}", absPath);
        return absPath;
    }

    public <T> String saveFile(String sheetName, List<T> data, Class<T> clazz) {
        ExcelUtil<T> util = new ExcelUtil<T>(clazz); // 使用clazz实例化ExcelUtil
        String filePath = util.exportExcelToFile(data, sheetName);
        log.info("导出文件成功: {}", filePath);
        return filePath;
    }

    public void cleanExportFileCache() {
        log.info("开始清理导出文件缓存");
        String os = System.getProperty("os.name").toLowerCase();
        String fileDir = os.contains("win")? RuoYiConfig.getWindowsProfile() : RuoYiConfig.getLinuxProfile();
        File folder = new File(fileDir);
        if (!folder.exists() || !folder.isDirectory()) {
            throw new RuntimeException("Invalid folder path: " + fileDir);
        }
        File[] files = folder.listFiles();
        if (files == null) {
            return;
        }
        for (File file : files) {
            if (file.isFile()) {
                processFile(file);
            }
        }
    }

    private void processFile(File file) {
        try {
            Path path = file.toPath();
            BasicFileAttributes attrs = Files.readAttributes(path, BasicFileAttributes.class);
            long creationTime = attrs.creationTime().toMillis();
            long currentTime = System.currentTimeMillis();
            long timeDifference = currentTime - creationTime;
            if (timeDifference > 48 * 60 * 60 * 1000) {
                if (file.delete()) {
                    log.info("Deleted file: " + file.getAbsolutePath());
                } else {
                    log.warn("Failed to delete file: " + file.getAbsolutePath());
                }
            }
        } catch (IOException e) {
            log.error("Error accessing file: " + file.getAbsolutePath());
            e.printStackTrace();
        }
    }


}
