package com.inspect.job.util;

import com.inspect.base.core.utils.StringUtils;
import com.inspect.job.domain.task.DataMsg;
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.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
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();
            System.out.println("连接sftp服务器异常！");
        }

    }

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

    }

    public static void main(String[] args) {
        FTPSClient ftps = new FTPSClient(false);

        try {
            ftps.connect("10.10.18.17", Integer.parseInt("21"));
            boolean bln = ftps.login("ftpuser", "atia2018");
            String remotePath = "1/2016/11/16/55/CCD";
            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);
                }
            }

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

    }

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

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

    }

    public void 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(StringUtils.SLASH);
            String tempPath = basePath;
            for (String dir : dirs) {
                if (null != dir && !dir.isEmpty()) {
                    tempPath = tempPath + StringUtils.SLASH + dir;

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

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

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

        File file = new File(saveFile);
        this.sftp.get(downloadFile, Files.newOutputStream(file.toPath()));
    }

    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 var5) {
            fileSize = -1L;
            if (var5.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 void uploadFile(DataMsg msg) {
        FTPSClient ftps = new FTPSClient(false);

        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.storeFile(msg.getFilePath() + StringUtils.SLASH + msg.getFileName(), msg.getInputStream());
                }

                FTPFile[] ftpFiles = ftps.listFiles(StringUtils.EMPTY);
                for (FTPFile file : ftpFiles) {
                    System.out.println(file.getName());
                }
            } else {
                System.out.println("==============2");
            }

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

    }

    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);
                }
            }

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

    }
}
