package org.jeecg.modules.bytedance.common.utils;

import org.apache.commons.codec.digest.DigestUtils;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Map;

public class LoadFileUtil {
    /**
     * 上传文件
     *
     * @param urlStr
     * @param savePath
     * @return
     * @throws IOException
     */
    public static String downLoadFromUrl(String urlStr, String savePath) {
        try {
            String fileName = AesEncryptUtil.getUrlDecoderString(urlStr.substring(urlStr.lastIndexOf("/") + 1));
            URL url = new URL(urlStr);

            System.setProperty("https.protocols", "TLSv1,TLSv1.1,TLSv1.2,SSLv3");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            //设置超时间为3秒
            conn.setConnectTimeout(60 * 1000);
            //防止屏蔽程序抓取而返回403错误
            conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
            //得到输入流
            InputStream inputStream = conn.getInputStream();
            //获取自己数组
            byte[] getData = readInputStream(inputStream);

            //文件保存位置
            File saveDir = new File(savePath);
            if (!saveDir.exists()) {
                saveDir.mkdirs();
            }
            String localPath = saveDir + File.separator + fileName;
            File file = new File(localPath);
            if (!file.exists()) {
                file.getParentFile().mkdirs();
            }
            FileOutputStream fos = new FileOutputStream(file);
            fos.write(getData);
            if (fos != null) {
                fos.close();
            }
            if (inputStream != null) {
                inputStream.close();
            }
            return localPath;
        } catch (Exception e) {
            return null;
        }


    }

    public static byte[] readInputStream(InputStream inputStream) throws IOException {
        byte[] buffer = new byte[1024];
        int len = 0;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        while ((len = inputStream.read(buffer)) != -1) {
            bos.write(buffer, 0, len);
        }
        bos.close();
        return bos.toByteArray();
    }


    /**
     * 删除文件
     *
     * @param path
     * @return
     */
    public static boolean delFile(String path) {
        boolean flag = false;
        File file = new File(path);
        if (!file.exists()) {
            return false;
        }
        try {
            flag = file.delete();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag;
    }

    /**
     * 获取文件md5
     *
     * @param path
     * @return
     * @throws IOException
     */
    public static String getMD5(String path) throws IOException {
        return DigestUtils.md5Hex(new FileInputStream(path));
    }

    public static String getMD5ByFile(FileInputStream inputStream) throws IOException {
        return DigestUtils.md5Hex(inputStream);
    }

    public static void checkFile(String filePackageName) {
        File file = new File(filePackageName);
        if (!file.exists()) {
            file.mkdir();
        }
    }

    public static String downloadByUrl(Map<String, Object> requestMap, String downloadPath, String urlStr, String token, String fileName) {

        try {
            StringBuilder postBody = null;
            if (!Check.isNull(requestMap)) {
                postBody = new StringBuilder();
                for (Map.Entry<String, Object> entry : requestMap.entrySet()) {
                    if (entry.getValue() == null) {
                        continue;
                    }
                    postBody.append(entry.getKey()).append("=").append(URLEncoder.encode(entry.getValue().toString(),
                            "utf-8")).append("&");
                }
                if (!requestMap.isEmpty()) {
                    postBody.deleteCharAt(postBody.length() - 1);
                }
            }

            URL url = new URL(urlStr + "?" + postBody);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            //设置超时间为3秒
            conn.setConnectTimeout(120 * 1000);
            //防止屏蔽程序抓取而返回403错误
            conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
            conn.setRequestProperty("Access-Token", token);
            //得到输入流
            InputStream inputStream = null;

            inputStream = conn.getInputStream();

            //获取自己数组
            byte[] getData = readInputStream(inputStream);

            //文件保存位置
            File saveDir = new File(downloadPath);
            if (!saveDir.exists()) {
                saveDir.mkdirs();
            }
            String filePath = downloadPath + fileName;

            File file = new File(saveDir + File.separator + fileName);
            FileOutputStream fos = new FileOutputStream(file);
            fos.write(getData);
            fos.close();
            inputStream.close();
            return filePath;
        } catch (IOException e) {
            e.printStackTrace();
        }


        return null;

    }


    public static InputStream getFileStream(String url) {
        try {
            HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
            connection.setReadTimeout(60000);
            connection.setConnectTimeout(60000);
            connection.setRequestMethod("GET");
            if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                InputStream inputStream = connection.getInputStream();
                return inputStream;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }


}
