package com.cf.imes.module.executor.util.file;

import cn.hutool.core.util.CharsetUtil;
import com.cf.imes.framework.common.exception.ServiceException;
import org.springframework.web.multipart.MultipartFile;

import jakarta.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;


import static com.cf.imes.module.infra.enums.ErrorCodeConstants.FILE_NOT_EXISTS;
import static com.cf.imes.module.executor.enums.ErrorCodeConstants.*;

/**
 * 文件相关工具类
 */
public class FileHelperUtil {

    // 文件下载
    public static void getFile(String route, HttpServletResponse response, String value) {
        // path是指想要下载的文件的路径
        File file = new File(route + File.separator + value);
        // 获取文件名
        String filename = file.getName();
        // 将文件写入输入流
        try (FileInputStream fis = new FileInputStream(file);
             OutputStream outputStream = new BufferedOutputStream(response.getOutputStream())) {
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);

            response.reset();
            response.setCharacterEncoding(CharsetUtil.UTF_8);
            response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, CharsetUtil.UTF_8));
            response.addHeader("Content-Length", "" + file.length());

            response.setContentType("application/octet-stream");
            outputStream.write(buffer);
            outputStream.flush();
        } catch (IOException ex) {
            throw new ServiceException(FILE_NOT_EXISTS);
        }
    }

    // 文件条件判断
    public static boolean checkFile(MultipartFile file,
                                    Long fileSize) {
        if (file.isEmpty()) {
            throw new ServiceException(FILE_NULL);
        }
        if (!(file.getOriginalFilename().endsWith(".xlsx") || file.getOriginalFilename().endsWith(".xls"))) {
            throw new ServiceException(FILE_FORMAT_ERROR);
        }
        if (file.getSize() > fileSize) {
            throw new ServiceException(FILE_EXCEED_SIZE);
        }
        if (file.getSize() == 0) {
            throw new ServiceException(FILE_CONTENT_NULL);
        }

        return true;
    }

    /**
     * 获取目录下第一个文件
     *
     * @param dirPath
     */
    public static File getFirstFile(String dirPath) {
        File dir = new File(dirPath);
        if (!dir.exists() || !dir.isDirectory()) {
            throw new ServiceException(FILE_NOT_EXISTS);
        }

        File[] files = dir.listFiles(File::isFile);
        if (files == null || files.length == 0) {
            throw new ServiceException(FILE_NOT_EXISTS);
        }

        return files[0];
    }
}
