package com.inkasso.factoring.file.util;

import com.github.pagehelper.util.StringUtil;
import com.inkasso.adapter.util.SpringUtil;
import com.inkasso.factoring.file.entity.FileStorageDO;
import com.inkasso.factoring.file.enums.FileTypeEnum;
import com.inkasso.factoring.file.service.FileService;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.UUID;

public class FileUtil {


    /**
     * 根据网络URL下载文件
     * @param fileUrl
     * @param fileLocal
     * @return
     * @throws Exception
     */
    public static boolean downloadFile(String fileUrl,String fileLocal) throws Exception {
        boolean flag=false;
        URL url = new URL(fileUrl);
        HttpURLConnection urlCon = (HttpURLConnection) url.openConnection();
        urlCon.setConnectTimeout(15000);
        urlCon.setReadTimeout(15000);
        int code = urlCon.getResponseCode();
        if (code != HttpURLConnection.HTTP_OK) {
            throw new Exception("文件读取失败");
        }
        //读文件流
        DataInputStream in = new DataInputStream(urlCon.getInputStream());
        DataOutputStream out = new DataOutputStream(new FileOutputStream(fileLocal));
        byte[] buffer = new byte[2048];
        int count = 0;
        while ((count = in.read(buffer)) > 0) {
            out.write(buffer, 0, count);
        }
        try {
            if(out!=null) {
                out.close();
            }
            if(in!=null) {
                in.close();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        flag=true;
        return flag;
    }

    /**
     * 在工程的目录下创建需要在线预览生成的文件夹
     **/
    public static String getFileOnlinePreviewPath() {
        String newPath = System.getProperty("user.dir") + File.separator + "src" + File.separator + "main"
                + File.separator + "resources" + File.separator + "static" + File.separator + "uploadFile";
        File directoryFile = new File(newPath);
        if (!(directoryFile.exists() && directoryFile.isDirectory())) {
            directoryFile.mkdirs();
        }
        return newPath;
    }

}
