package cn.quantgroup.customer.util;

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.*;
import java.lang.reflect.Field;
import java.nio.charset.Charset;
import java.util.Properties;
import java.util.Vector;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class SFTPUtil {
    private final Logger logger = 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();
            Class<ChannelSftp> c = ChannelSftp.class;
            Field f = c.getDeclaredField("server_version");
            f.setAccessible(true);
            // chSftp = (ChannelSftp) channel;
            this.sftp = (ChannelSftp)channel;
            f.set(sftp, 2);
            sftp.setFilenameEncoding("utf-8");
            this.logger.info("pwd = [{}]", this.sftp.pwd());
        } catch (JSchException var4) {
            var4.printStackTrace();
        } catch (SftpException var5) {
            var5.printStackTrace();
        }catch (Exception var5){

        }

    }

    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 {
            String[] dirs = basePath.split("/");
            String[] var8 = dirs;
            int var9 = dirs.length;
            for(int var10 = 0; var10 < var9; ++var10) {
                String dir = var8[var10];
                if (null != dir && !"".equals(dir)) {
                    this.sftp.cd(dir);
                }
            }
            if(this.isDirExist(basePath+"/"+directory)){
                this.sftp.cd(directory);
            }else{
                this.sftp.mkdir(directory);
                this.sftp.cd(directory);
            }

        } catch (SftpException var14) {
            String tempPath = "/"+directory;
            String[] dirs = tempPath.split("/");
            String[] var8 = dirs;
            int var9 = dirs.length;
            for(int var10 = 0; var10 < var9; ++var10) {
                String dir = var8[var10];
                if (null != dir && !"".equals(dir)) {
                    //tempPath = tempPath + "/" + dir;
                    try {
                        this.sftp.cd(dir);
                    } catch (SftpException var13) {
                        this.sftp.mkdir(dir);
                        this.sftp.cd(dir);
                    }
                }
            }
        }*/
        createDir(basePath+directory);

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

    public void download(String directory, String downloadFile, String saveDirectory, String saveFile) throws SftpException, FileNotFoundException {
        String[] dirs = directory.split("/");
        String[] var8 = dirs;
        int var9 = dirs.length;
        for(int var10 = 0; var10 < var9; ++var10) {
            String dir = var8[var10];
            if (null != dir && !"".equals(dir)) {
                this.sftp.cd(dir);
            }
        }
        File file = new File(saveDirectory, saveFile);
        this.sftp.get(downloadFile, new FileOutputStream(file));
    }

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

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

    public byte[] download(String directory, String downloadFile){
        ByteArrayOutputStream fileOutputStream = new ByteArrayOutputStream();
        String[] dirs = directory.split("/");
        String[] var8 = dirs;
        int var9 = dirs.length;
        for(int var10 = 0; var10 < var9; ++var10) {
            String dir = var8[var10];
            if (null != dir && !"".equals(dir)) {
                try {
                    this.sftp.cd(dir);
                } catch (SftpException e) {
                    e.printStackTrace();
                }
            }
        }
        try {
            this.sftp.get(downloadFile,fileOutputStream);
        } catch (SftpException e) {
            e.printStackTrace();
        }
        byte[] fileData = fileOutputStream.toByteArray();
        //byte[] fileData= IOUtils.readNBytes(is, is.available());
        return fileData;


    }

    public byte[] download(String directory,String downloadFile,
                           String userName,String password,String host,int port) throws SftpException, IOException {
        if (StringUtils.isNotBlank(directory)){
            downloadFile = directory.concat("/"+downloadFile);
        }
        ByteArrayOutputStream fileOutputStream = new ByteArrayOutputStream();
        JSch jsch = null;
        Session session = null;
        Channel channel = null;
        ChannelSftp channelSftp = null;
        try {
            jsch = new JSch();
            session = jsch.getSession(userName, host,port);
            session.setPassword(password.getBytes(Charset.forName("ISO-8859-1")));
            Properties config = new Properties();
            config.put("StrictHostKeyChecking", "no");
            session.setConfig(config);
            //session.setTimeout(SO_TIME_OUT);
            //log.info("连接 SFTP 服务器 " + baseInfo.getHost() + ":" + baseInfo.getPort());
            session.connect();
            channel = session.openChannel("sftp");
            channel.connect();
            channelSftp = (ChannelSftp) channel;
            if (channelSftp == null || session == null || !session.isConnected() || !channelSftp.isConnected()) {
                //log.info("SFTP channel 已经关闭");
                throw new Exception("系统内部异常");
            }
            channelSftp.get(downloadFile, fileOutputStream);
            //log.info("SFTP.client.下载成功 文件名={}", fileName);
            return fileOutputStream.toByteArray();
        } catch (Exception e) {
            //log.error("SFTP.client.创建连接失败");
            return null;
        } finally {
            if (channelSftp != null) {
                channelSftp.disconnect();
            }
            if (channel != null) {
                channel.disconnect();
            }
            if (session != null) {
                session.disconnect();
            }
        }



    }

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

    public void createDir(String createPath) {
        try {
            if (this.isDirExist(createPath)) {
                this.sftp.cd(createPath);
                return;
            }

            String[] pathArry = createPath.split("/");
            StringBuffer filePath = new StringBuffer("/");
            String[] var4 = pathArry;
            int var5 = pathArry.length;

            for(int var6 = 0; var6 < var5; ++var6) {
                String path = var4[var6];
                if (!path.equals("")) {
                    filePath.append(path + "/");
                    if (this.isDirExist(filePath.toString())) {
                        this.sftp.cd(filePath.toString());
                    } else {
                        this.sftp.mkdir(filePath.toString());
                        this.sftp.cd(filePath.toString());
                    }
                }
            }
        } catch (SftpException var8) {
            var8.printStackTrace();
        }

    }

    public boolean isDirExist(String directory) {
        boolean isDirExistFlag = false;

        try {
            SftpATTRS sftpATTRS = this.sftp.lstat(directory);
            isDirExistFlag = true;
            return sftpATTRS.isDir();
        } catch (Exception var4) {
            if (var4.getMessage().toLowerCase().equals("no such file")) {
                isDirExistFlag = false;
            }

            return isDirExistFlag;
        }
    }

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

    public static void main(String[] args) {
        //SFTPUtil sftp = new SFTPUtil("lhphy", "47.105.211.91", 22223, "MIIEpQIBAAKCAQEAzCJdHIHjBobXq8S+Vq6IoAY7y3u98KQ1dyA6Ixpa83bw0xZJ0yA/vrcNxueyUesdL7DaG/4kruAdiCeLukYqlmJR+SsFcBUxnB4zYSrWx106CoLjPujvv1DvFgPacDGyp4+e7ifGt/RQlAPONQ+XbaHDHjr6R/0i/93Gm+/yn+/wQvsGUVOqE4kSvpY+36mcVyAgXf2f7Q5YvGsuA7Y7wx0tqU/M/7RI2cRYa3/PumMtBAvx/3Ny17is4I+8RRCq5B/UjOiwsSd391QWMpT0B3T5tO9stpMXLL1Vfm/O4lBUIWkEJsGBqjtgLp7LUpCzDyOGW7+Bi+kDTo5Z1huvfwIDAQABAoIBAQDHcX+lnaXRN6e6NDR/fnEQYGbFjbXrSpTOOhdzOonIO9pZcvpYI7cEP9dfEfsgnGVcth6zoN/4WBGieHjFW066tX8/we/DLYHV9Y/fjLph+Mz/fhhG29F6C7o8uTEP0w6pNeJi70vxaOvdYcZ0AzLBM33uqFLmSQWMFgO5UXutFEDtgi6y6w067CFHq0LEn6PrHZqnevKsPCBMdEXQcTfDaL3JHQGGrIw7WGsi6c6uVk6EVSoSeag0mV6gLfQZzP7zf4oSTZb1Oxt10mk3hVrQV1FiNtHFQpfR9TBCrJBiRER0QQOh/PHet6lXzQ9SQbswLVsbL9asuAS7zOoFwWRBAoGBAPsjwf6waEB8YwPgL8MpD9cRd+VlwjJD9HQGSAr8IHgMNgrwhB2EZx+GOqSqI4FaXhQjb2Safs2POLZOArDmSDSajT7E6etue3c+P5MP/hprjNaSidaEcXsF/eCMjzntZT5HbHNCTHD0DoT5GkVj50UCfz3PHzQxTHV0pk4B2SufAoGBANAVuRIpwBOtF7RIDAeBi3OMdO6fTw3i3rZBco6qqGwyxt/d6BCvEGUuh3s3pcKcNfdRr6AeZRiwtgk8uu7dcwZBdF6TnCQqzJefReyVlVFDpyt44dKVDtOlckwc+BcaM56NHCWrGEJAwxAzl84rAywxktvT63x+LfY8w5KUyPAhAoGBAPM0G6fzWeIpExIrxtUuLKLPzdYfB0L6P/8kHhxVMXRQDv3lEWwsTlle+eeAxEV+J+FEt5krbGTQr9EMFtsNBxu6F9KTixxtr684XwSh1ifrw0YAPu+47tR+Zu9P71vfo83+CO5NZA12q6DmQySzrMFNu781lzhKDYspXevpKlBtAoGBALPZUrCELWPUQ5yqeNsz+JfSWm60etuBrwTP5HeywQdji8iKP73L0dviL28sVbSy12H/1FAMdUy1z2CEgP1bocNSZ4YnBtmrtFGIdCNb1kb6tk44mNYtxzbe1L88eqFdICh1xlI4YytAVlh2f0rOmltkLY6ax/o+BPPC6TaUKmiBAoGASC1VYOzpelcN0ne3RfOrTDzRH3lQzGTh7E+2UxsVpkdxJg0N4e47MGKpGyylxEiuqpcoc9w7ec+IqylcL5Hx2jzDLx4OJHagtZVv8Gx9tixG6+vAdjjl7E38HS5WQcFJzQRAyktCeeoiLYIA3UvSN0GOXqDPAkFzPtX853APRwQ=");
        SFTPUtil sftp = new SFTPUtil("lzshopkf","Q0lEkbamFm4aKZEi","172.27.8.47",22);
        sftp.login();

        try {
            /*boolean has = sftp.isDirExist("/lzshopkf/transaction/交易凭证/2张三");
            System.out.println(has);
            if (!has) {
                sftp.createDir("/lzshopkf/transaction/交易凭证/2账务");
            }*/
            byte [] bytes = sftp.download("/lzshopkf/transaction","交易凭证");
        } catch (Exception var3) {
            var3.printStackTrace();
        }

        sftp.logout();
    }
}

