package com.inspect.base.core.utils;

import com.inspect.base.core.domain.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.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
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 static Logger log = LoggerFactory.getLogger(SFTPUtil.class);
    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("10.85.223.43", Integer.parseInt("10013"));
            ftps.login("dlftp", "dlftp");
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("连接sftp服务器异常！");
        }
    }

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

        try {
            ftps.connect("10.10.18.17", Integer.parseInt("990"));
            boolean bln = ftps.login("xgftp", "Xg369246$");
            if (bln) {
                decorateSFTP(ftps);
                String str = new String("你好啊".getBytes("UTF-8"), "iso-8859-1");
                boolean fssa = ftps.makeDirectory("/home/xgftp/" + str);
                System.out.println(fssa);
            } else {
                System.out.println("==============2");
            }

            ftps.logout();
        } catch (Exception 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("/");
            String tempPath = basePath;

            for (String dir : dirs) {
                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);
    }

    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);
            } catch (SftpException e) {
                e.printStackTrace();
                isDirExistFlag = false;
            }
        }

        return isDirExistFlag;
    }

    public static void UploadFile(DataMsg msg) {
        FTPSClient ftps = new FTPSClient(true);

        try {
            ftps.connect(msg.getIp(), Integer.parseInt(msg.getPort()));
            boolean bln = ftps.login(msg.getUsername(), msg.getPassword());
            if (bln) {
                decorateSFTP(ftps);
                if (msg.getType().equals("0")) {
                    ftps.makeDirectory(msg.getFilePath());
                    ftps.storeFile(msg.getFilePath() + "/" + msg.getFileName(), msg.getInputStream());
                }

                System.out.println("====上传路径====" + msg.getFilePath() + "/" + msg.getFileName() + "====输入流长度=" + msg.getInputStream().available());
            } else {
                System.out.println("=====登录失败！=========");
            }

            FTPFile[] ftpFiles = ftps.listFiles(msg.getFilePath());
            for (FTPFile file : ftpFiles) {
                System.out.println(file.getName());
                if (file.getName().equals(msg.getFileName())) {
                    System.out.println("====上传成功！====");
                    break;
                }
            }

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

    }

    public static boolean UploadFileInfo(DataMsg msg) {
        boolean flag = !StringUtils.isNotEmpty(msg.getUploadType()) || !msg.getUploadType().equals("1");
        FTPSClient ftps = new FTPSClient(flag);
        boolean sa = false;

        try {
            ftps.connect(msg.getIp(), Integer.parseInt(msg.getPort()));
            boolean bln = ftps.login(msg.getUsername(), msg.getPassword());
            if (!bln) {
                System.out.println("==============2");
            } else {
                decorateSFTP(ftps);
                if (msg.getType().equals("0")) {
                    if (msg.getFilepathList() != null && !msg.getFilepathList().isEmpty()) {
                        String pp = "";

                        for (int i = 0; i < msg.getFilepathList().size(); ++i) {
                            String aa = pp + "/" + msg.getFilepathList().get(i);
                            System.out.println(aa);
                            boolean flag111 = ftps.makeDirectory(aa);
                            System.out.println(flag111);
                        }
                    }

                    ftps.storeFile(msg.getFilePath() + "/" + msg.getFileName(), msg.getInputStream());
                }

                FTPFile[] ftpFiles = ftps.listFiles(msg.getFilePath());
                for (FTPFile file : ftpFiles) {
                    System.out.println(file.getName());
                    if (file.getName().equals(msg.getFileName())) {
                        sa = true;
                        break;
                    }
                }

                System.out.println("==============1");
            }

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

        return sa;
    }

    public static boolean uploadFileForXml(DataMsg msg) {
        boolean flag = "true".equals(msg.getIsImplicit());
        FTPSClient ftps = new FTPSClient(flag);
        boolean sa = false;
        try {
            log.info("[FTP] ip: {}, port: {}, username: {}, password: {}, isImplicit: {}", msg.getIp(), msg.getPort(), msg.getUsername(), msg.getPassword(), flag);
            ftps.connect(msg.getIp(), Integer.parseInt(msg.getPort()));
            boolean bln = ftps.login(msg.getUsername(), msg.getPassword());
            if (!bln) {
                System.out.println("==============2");
            } else {
                decorateSFTP(ftps);
                if (StringUtils.isNotEmpty(msg.getFilePath())) {
                    if (!msg.getFilePath().startsWith(StringUtils.SLASH)) {
                        msg.setFilePath(msg.getBasePath() + StringUtils.SLASH + msg.getFilePath());
                    }

                    String[] split = msg.getFilePath().split(StringUtils.SLASH);
                    ftps.changeWorkingDirectory(StringUtils.SLASH);
                    for (String str : split) {
                        if (!ftps.changeWorkingDirectory(str)) {
                            ftps.makeDirectory(str);
                            ftps.changeWorkingDirectory(str);
                        }
                    }
                }

                ftps.storeFile(msg.getFileName(), msg.getInputStream());
                FTPFile[] ftpFiles = ftps.listFiles(msg.getFilePath());
                for (FTPFile file : ftpFiles) {
                    System.out.println(file.getName());
                    if (file.getName().equals(msg.getFileName())) {
                        sa = true;
                        break;
                    }
                }

                System.out.println("==============1");
            }

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

        return sa;
    }

    public static boolean UploadFileInfoAgain(DataMsg msg) {
        boolean flag = !StringUtils.isNotEmpty(msg.getUploadType()) || !msg.getUploadType().equals("1");

        FTPSClient ftps = new FTPSClient(flag);
        boolean sa = false;

        try {
            ftps.connect(msg.getIp(), Integer.parseInt(msg.getPort()));
            boolean bln = ftps.login(msg.getUsername(), msg.getPassword());
            if (!bln) {
                System.out.println("==============2");
            } else {
                decorateSFTP(ftps);
                if (msg.getType().equals("0")) {
                    String pp;
                    if (msg.getFilepathList() != null && !msg.getFilepathList().isEmpty()) {
                        pp = msg.getBasePath();

                        for (int i = 0; i < msg.getFilepathList().size(); ++i) {
                            String aa = pp + "/" + (String) msg.getFilepathList().get(i);
                            String str = new String(aa.getBytes("UTF-8"), "iso-8859-1");
                            System.out.println(str);
                            boolean flag111 = ftps.makeDirectory(str);
                            System.out.println(flag111);
                            ftps.changeWorkingDirectory(str);
                        }
                    }

                    pp = new String(msg.getFileName().getBytes("UTF-8"), "iso-8859-1");
                    ftps.storeFile(pp, msg.getInputStream());
                }

                FTPFile[] ftpFiles = ftps.listFiles(msg.getFilePath());
                for (FTPFile file : ftpFiles) {
                    System.out.println(file.getName());
                    if (file.getName().equals(msg.getFileName())) {
                        sa = true;
                        break;
                    }
                }

                System.out.println("==============1");
            }

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

        return sa;
    }

    public static InputStream downFileInfo(DataMsg msg) {
        boolean flag = true;
        InputStream sbs = null;
        if (StringUtils.isNotEmpty(msg.getUploadType()) && msg.getUploadType().equals("1")) {
            flag = false;
        }

        FTPSClient ftps = new FTPSClient(flag);
        boolean var4 = false;

        try {
            ftps.connect(msg.getIp(), Integer.parseInt(msg.getPort()));
            boolean bln = ftps.login(msg.getUsername(), msg.getPassword());
            if (bln) {
                decorateSFTP(ftps);
                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                ftps.retrieveFile(msg.getFilePath(), byteArrayOutputStream);
                byte[] buffer = byteArrayOutputStream.toByteArray();
                sbs = new ByteArrayInputStream(buffer);
                System.out.println("==============1");
            } else {
                System.out.println("==============2");
            }

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

        return sbs;
    }

    public static InputStream downFile(DataMsg msg) {
        boolean flag = true;
        InputStream sbs = null;
        if (StringUtils.isNotEmpty(msg.getUploadType()) && msg.getUploadType().equals("1")) {
            flag = false;
        }

        FTPSClient ftps = new FTPSClient(flag);

        try {
            ftps.connect(msg.getIp(), Integer.parseInt(msg.getPort()));
            boolean bln = ftps.login(msg.getUsername(), msg.getPassword());
            if (bln) {
                decorateSFTP(ftps);
                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                boolean fla = ftps.retrieveFile(msg.getFilePath(), byteArrayOutputStream);
                byte[] buffer = byteArrayOutputStream.toByteArray();
                sbs = new ByteArrayInputStream(buffer);
                System.out.println("======下载" + fla + "========");
            } else {
                System.out.println("========登录失败！======");
            }

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

        return sbs;
    }

    private static void decorateSFTP(FTPSClient ftps) throws IOException {
        ftps.enterLocalPassiveMode();
        ftps.setControlEncoding("UTF-8");
        ftps.enterLocalPassiveMode();
        ftps.setFileType(2);
        ftps.setFileTransferMode(10);
        ftps.execPROT("P");
    }
}
