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

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.framework.common.exception.util.ServiceExceptionUtil.exception;
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)) {
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();

            response.reset();
            response.setCharacterEncoding("UTF-8");
            response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
            response.addHeader("Content-Length", "" + file.length());
            OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            outputStream.write(buffer);
            outputStream.flush();
        } catch (IOException ex) {
            throw exception(FILE_NOT_EXISTS);
        }
    }

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

        return true;
    }
}
