package com.infoepoch.pms.dispatchassistant.common.utils;


import org.apache.commons.io.FileUtils;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;


/**
 * 文件工具类
 */
public class FileUtil {

    /**
     * 获取classPath路径下的模板文件
     *
     * @param request          请求
     * @param templateFilePath 模板文件路径(示例："static/template/demo.docx")
     * @return
     * @throws IOException
     */
    public static File getFile(HttpServletRequest request, String templateFilePath) throws IOException {
        File newFile;
        InputStream inputStream = null;
        try {
            Resource resource = new ClassPathResource(templateFilePath);
            inputStream = resource.getInputStream();
            String realPath = request.getSession().getServletContext().getRealPath("");
            String filePath = realPath + resource.getFilename();
            newFile = new File(filePath);
            //判断目标文件所在目录是否存在
            if (!newFile.getParentFile().exists()) {
                //如果目标文件所在的目录不存在，则创建父目录
                newFile.getParentFile().mkdirs();
            }
            FileUtils.copyInputStreamToFile(inputStream, newFile);
        } catch (IOException e) {
            throw new IOException("未找到文件，报错：" + e.getMessage());
        } finally {
            if (inputStream != null)
                inputStream.close();
        }
        return newFile;
    }

    /**
     * 获取classPath路径下的模板文件
     *
     * @param templateFilePath 模板文件路径(示例："static/template/demo.docx")
     * @return
     * @throws IOException
     */
    public static File getFile(String templateFilePath) throws IOException {
        File newFile;
        InputStream inputStream = null;
        try {
            Resource resource = new ClassPathResource(templateFilePath);
            inputStream = resource.getInputStream();
            ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
            HttpSession session = attr.getRequest().getSession();
            String realPath = session.getServletContext().getRealPath("");
            String filePath = realPath + resource.getFilename();
            newFile = new File(filePath);
            //判断目标文件所在目录是否存在
            if (!newFile.getParentFile().exists()) {
                //如果目标文件所在的目录不存在，则创建父目录
                newFile.getParentFile().mkdirs();
            }
            FileUtils.copyInputStreamToFile(inputStream, newFile);
        } catch (IOException e) {
            throw new IOException("未找到文件，报错：" + e.getMessage());
        } finally {
            if (inputStream != null)
                inputStream.close();
        }
        return newFile;
    }

    public static File getAbsFile(String absFilePath) {
        return new File(absFilePath);
    }

    /**
     * @Description: 获取临时文件路径（使用完成后，需删除文件）
     * @Param: [fileName]
     * @Author: zhangyd
     */
    public static String getTempAbsPath(String fileName) {
        ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
        HttpSession session = attr.getRequest().getSession();
        String realPath = session.getServletContext().getRealPath("");
        return realPath + fileName;
    }

    /**
     * 下载文件
     *
     * @param fileAbsPath
     * @throws FileNotFoundException
     */
    public static void download(String fileAbsPath) {
        ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
        HttpServletResponse response = attr.getResponse();
        File file = new File(fileAbsPath);
        // 取得文件名。
        String filename = file.getName();

        // 设置输出的格式
        response.reset();
        response.setCharacterEncoding("UTF-8");
        response.addHeader("Content-Disposition", "attachment; filename=\"" + new String(filename.getBytes()) + "\"");
        response.addHeader("Content-Length", "" + file.length());

        try (OutputStream out = response.getOutputStream()){
            Path path = file.toPath();
            Files.copy(path, out);
            out.flush();
        }catch(IOException e){
            e.printStackTrace();
        }
    }
}
