package com.ann.demo.utils;

import com.ann.demo.entity.constant.AliasName;
import org.apache.commons.net.ftp.FTPClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.lang.reflect.Field;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Objects;

/**
 * @Description 下载工具
 * @Date 2019/7/2 16:56
 * @Created by  ljx
 */
public class DownloadUtils {

    static final Logger logger = LoggerFactory.getLogger(DownloadUtils.class);


    /**
     * 从网络Url中下载文件
     *
     * @param urlStr
     * @param fileName
     * @param savePath
     * @throws IOException
     */
    public static void downLoadByUrl(String urlStr, String fileName, String savePath) throws IOException {
        URL url = new URL(urlStr);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        //设置超时间为5秒
        conn.setConnectTimeout(5 * 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.mkdir();
        }
        File file = new File(saveDir + File.separator + fileName);
        FileOutputStream fos = new FileOutputStream(file);
        fos.write(getData);
        if (fos != null) {
            fos.close();
        }
        if (inputStream != null) {
            inputStream.close();
        }
        System.out.println("info:" + url + " download success");
    }


    /**
     * 从输入流中获取字节数组
     *
     * @param inputStream
     * @return
     * @throws IOException
     */
    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();
    }

    //从共享目录下载文件
    public static boolean cmdFile(String path, File imageFile) {
        boolean result = false;
        BufferedInputStream in = null;
        BufferedOutputStream out = null;
        try {
            Runtime.getRuntime().exec("net use \\10.6.0.74 his /user:his");
            in = new BufferedInputStream(new FileInputStream(path));
            out = new BufferedOutputStream(new FileOutputStream(imageFile));

            byte[] buffer = new byte[1024];
            while (in.read(buffer) != -1) {
                out.write(buffer);
                buffer = new byte[1024];
            }
            out.flush();
            result = true;
        } catch (IOException e) {
            //   FileUtils.deleteImageFile(imageFile);
            logger.error("出错咯！错误信息:" + e);
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException e) {
                //  FileUtils.deleteImageFile(imageFile);
                e.printStackTrace();
            }
        }
        return result;
    }

    public static String downloadImageFile(String address, String type, File imageFile) throws Exception {
        String url = "";
        String path = "";
        Integer port = 21;

        address = address.substring(address.indexOf("/") + 2, address.length());
        path = address.substring(address.indexOf("/"), address.length());
        //处理url 以及端口 如果有端口 截取 否则默认端口
        if (address.indexOf(":") != -1 && address.indexOf("/") != -1) {
            port = Integer.parseInt(address.substring(address.indexOf(":") + 1, address.indexOf("/")));
            url = address.substring(0, address.indexOf(":"));
        }
        String userName = "common";
        String password = "common";

        FTPClient ftpClient = FTPUtil.connectFtpServer(url, port, userName, password);
        if (FTPUtil.downloadFtp(path, ftpClient, imageFile)) {
            return imageFile.getAbsolutePath();
        }
        return null;
    }

}
