package com.emr.util;

import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;

@Component
public class UploadUtil {

    /**
     * 解析上传的压缩文件
     *
     * @param request 请求
     * @param file    上传文件
     * @return
     * @throws Exception
     */
    public static String resolveCompressUploadFile(HttpServletRequest request, MultipartFile file, String path) throws Exception {

        /* 截取后缀名 */
        if (file.isEmpty()) {
            return "文件不能为空";
        }
        String fileName = file.getOriginalFilename();
        int pos = fileName.lastIndexOf(".");
        String extName = fileName.substring(pos + 1).toLowerCase();
        //判断上传文件必须是zip或者是rar否则不允许上传
        if (!extName.equals("zip") && !extName.equals("rar")) {
            throw new Exception("上传文件格式错误，请重新上传");
        }
        // 时间加后缀名保存
        //SimpleDateFormat dateFormat = new SimpleDateFormat ("yyyy-MM-dd");
        //String format = dateFormat.format (new Date());
        String saveName = UUIDUtils.getUUID() + "." + extName; //353fdsfdfsdfdsf7887878.zip
        //文件名
        String saveFileName = saveName.substring(0, saveName.lastIndexOf("."));//353fdsfdfsdfdsf7887878
        // 根据服务器的文件保存地址和原文件名创建目录文件全路径
        //设置上传文件夹的真实路径
        //String realPath = request.getSession().getServletContext().getRealPath("/upfile");
        File pushFile = new File(path + "/" + saveFileName + "/" + saveName);//存放压缩包文件的路径下的压缩文件

        File descFile = new File(path + "/" + saveFileName);//存放压缩包文件的路径
        if (!descFile.exists()) {
            descFile.mkdirs();
        }
        //解压目的文件
        String descDir = path + "/" + saveFileName + "/";

        file.transferTo(pushFile);

        //开始解压zip
        if (extName.equals("zip")) {
            CompressFileUtils.unZipFiles(pushFile, descDir);

        } else if (extName.equals("rar")) {
            //开始解压rar
            CompressFileUtils.unRarFile(pushFile.getAbsolutePath(), descDir);
        } else {
            throw new Exception("文件格式不正确不能解压");
        }

        return descDir;
    }

    /**
     * 解压后生成MultipartFile集合
     *
     * @param strPath
     * @return
     */
    /*public static List<MultipartFile> getMultipartFileListByPath(String strPath) throws IOException {

        File dir = new File(strPath);
        File[] files = dir.listFiles(); // 该文件目录下文件全部放入数组
        List<MultipartFile> multipartFiles = new ArrayList<>();
        if (files != null) {
            for (File file : files) {
                FileInputStream input = new FileInputStream(file);
                MultipartFile multipartFile = new MockMultipartFile(file.getName(), file.getName(), "text/plain", input);
                multipartFiles.add(multipartFile);
                input.close();
            }
        }
        return multipartFiles;
    }*/

}
