package com.inspect.job.domain.task;

import com.inspect.base.core.utils.StringUtils;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpATTRS;
import com.jcraft.jsch.SftpException;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Properties;
import java.util.Vector;

import org.apache.commons.io.IOUtils;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPSClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class SFTPUtil {
    private transient Logger log = LoggerFactory.getLogger(this.getClass());
    private ChannelSftp sftp;
    private Session session;
    private String username;
    private String password;
    private String privateKey;
    private String host;
    private int port;

    public SFTPUtil(String username, String password, String host, int port) {
        this.username = username;
        this.password = password;
        this.host = host;
        this.port = port;
    }

    public SFTPUtil(String username, String host, int port, String privateKey) {
        this.username = username;
        this.host = host;
        this.port = port;
        this.privateKey = privateKey;
    }

    public SFTPUtil() {
    }

    public void login() {
        try {
            JSch jsch = new JSch();
            if (this.privateKey != null) {
                jsch.addIdentity(this.privateKey);
            }

            this.session = jsch.getSession(this.username, this.host, this.port);
            if (this.password != null) {
                this.session.setPassword(this.password);
            }

            Properties config = new Properties();
            config.put("StrictHostKeyChecking", "no");
            this.session.setConfig(config);
            this.session.connect();
            Channel channel = this.session.openChannel("sftp");
            channel.connect();
            this.sftp = (ChannelSftp) channel;
        } catch (JSchException e) {
            e.printStackTrace();
        }

    }

    public void loginBy() {
        try {
            FTPSClient ftps = new FTPSClient(true);
            ftps.connect("0.10.18.17", Integer.parseInt("10013"));
            ftps.login("xgftp", "Xg369246$");
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("连接sftp服务器异常！");
        }

    }

    public static void main(String[] args) throws FileNotFoundException {
        File file = new File("D:\\llc\\dl\\doc\\cmd.txt");
        InputStream is = new FileInputStream(file);
        DataMsg dataMsg = new DataMsg();
        dataMsg.setInputStream(is);
        dataMsg.setUserName("tgy");
        dataMsg.setPassword("test123456");
        dataMsg.setIp("localhost");
        dataMsg.setPort("10012");
        dataMsg.setType("0");
        dataMsg.setFilePath("2");
        dataMsg.setFileName("cmd1.txt");
        dataMsg.setBasePath("/home/tgy/");
        uploadFile(dataMsg);
    }

    public static InputStream doGetRequestForInputStream(String urlStr) {
        String DEFAULT_CHARSET = "utf-8";
        int DEFAULT_TIME_OUT = 5000;
        InputStream is = null;
        ByteArrayOutputStream os = null;

        try {
            URL url = new URL(urlStr);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestProperty("Content-Type", "plain/text;charset=" + DEFAULT_CHARSET);
            conn.setRequestProperty("charset", DEFAULT_CHARSET);
            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.setRequestMethod("GET");
            conn.setReadTimeout(DEFAULT_TIME_OUT);
            conn.connect();
            is = conn.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
        }

        return is;
    }

    public void logout() {
        if (this.sftp != null && this.sftp.isConnected()) {
            this.sftp.disconnect();
        }

        if (this.session != null && this.session.isConnected()) {
            this.session.disconnect();
        }

    }

    public String upload(String basePath, String directory, String sftpFileName, InputStream input) throws SftpException {
        try {
            this.sftp.cd(basePath);
            this.sftp.cd(directory);
        } catch (SftpException var14) {
            String[] dirs = directory.split("/");
            String tempPath = basePath;
            String[] var8 = dirs;
            int var9 = dirs.length;

            for (int var10 = 0; var10 < var9; ++var10) {
                String dir = var8[var10];
                if (null != dir && !dir.isEmpty()) {
                    tempPath = tempPath + "/" + dir;

                    try {
                        this.sftp.cd(tempPath);
                    } catch (SftpException var13) {
                        this.sftp.mkdir(tempPath);
                        this.sftp.cd(tempPath);
                    }
                }
            }
        }

        this.sftp.put(input, sftpFileName);
        return basePath;
    }

    public void download(String directory, String downloadFile, String saveFile) throws SftpException, FileNotFoundException {
        if (directory != null && !directory.isEmpty()) {
            this.sftp.cd(directory);
        }

        File file = new File(saveFile);
        this.sftp.get(downloadFile, new FileOutputStream(file));
    }

    public byte[] download(String directory, String downloadFile) throws SftpException, IOException {
        if (directory != null && !directory.isEmpty()) {
            this.sftp.cd(directory);
        }

        InputStream is = this.sftp.get(downloadFile);
        return IOUtils.toByteArray(is);
    }

    public void delete(String directory, String deleteFile) throws SftpException {
        this.sftp.cd(directory);
        this.sftp.rm(deleteFile);
    }

    public Vector<?> listFiles(String directory) throws SftpException {
        return this.sftp.ls(directory);
    }

    public long getFileSize(String srcSftpFilePath) {
        long fileSize;
        try {
            SftpATTRS sftpAttrs = this.sftp.lstat(srcSftpFilePath);
            fileSize = sftpAttrs.getSize();
        } catch (Exception e) {
            fileSize = -1L;
            if (e.getMessage().equalsIgnoreCase("no such file")) {
                fileSize = -2L;
            }
        }

        return fileSize;
    }

    public boolean mkDir(String basePath, String date) {
        boolean isDirExistFlag = true;
        SftpATTRS sftpATTRS = null;

        try {
            sftpATTRS = this.sftp.lstat(basePath + date);
        } catch (Exception var8) {
            try {
                this.sftp.cd(basePath);
                this.sftp.mkdir(date);
                isDirExistFlag = true;
            } catch (SftpException e) {
                e.printStackTrace();
                isDirExistFlag = false;
            }
        }

        return isDirExistFlag;
    }

    public static boolean uploadFile(DataMsg msg) {
        boolean rel = true;
        FTPSClient ftps = new FTPSClient(true);

        try {
            ftps.connect(msg.getIp(), Integer.parseInt(msg.getPort()));
            boolean bln = ftps.login(msg.getUserName(), msg.getPassword());
            if (bln) {
                ftps.setFileType(2);
                if (msg.getType().equals("0")) {
                    ftps.enterLocalPassiveMode();
                    makeDirectories(msg.getFilePath(), ftps);
                    rel = ftps.storeFile(msg.getBasePath() + msg.getFilePath() + "/" + msg.getFileName(), msg.getInputStream());
                    System.out.println(rel);
                }

                System.out.println("==============1" + msg.getFilePath() + "/" + msg.getFileName());
            } else {
                System.out.println("==============2");
            }

            ftps.logout();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return rel;
    }

    public static void mkdir(FTPSClient ftps, String path) throws IOException {
        String[] split = path.split(StringUtils.SLASH);
        ftps.changeWorkingDirectory(StringUtils.SLASH);
        for (String str : split) {
            if (!StringUtils.isEmpty(str)) {
                boolean exists = false;
                FTPFile[] ftpFiles = ftps.mlistDir();
                for (FTPFile ftpFile : ftpFiles) {
                    if (ftpFile.isDirectory() && ftpFile.getName().equals(str)) {
                        exists = true;
                    }
                }

                if (!exists) {
                    ftps.makeDirectory(str);
                }

                ftps.changeWorkingDirectory(str);
            }
        }

    }

    public static void makeDirectories(String remotePath, FTPSClient ftps) {
        try {
            String[] split = remotePath.split(StringUtils.SLASH);
            for (String str : split) {
                if (!StringUtils.isNull(str) && !ftps.changeWorkingDirectory(str)) {
                    boolean makeDirectory = ftps.makeDirectory(str);
                    boolean changeWorkingDirectory = ftps.changeWorkingDirectory(str);
                    System.out.println(str + "创建：" + makeDirectory + ";切换：" + changeWorkingDirectory);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
