package com.jiayue.ipfcst.ftpsftp.service;

import com.jcraft.jsch.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.utils.IOUtils;
import org.springframework.stereotype.Service;

import java.io.*;
import java.util.ArrayList;
import java.util.Properties;
import java.util.Vector;

@Service
@Slf4j
public class ContinueSFTPService {
  private String Type = "sftp";

  private ChannelSftp sftp;
  private Session session;
  private String username;
  private String password;
  private String privateKey;
  private String host;
  private int port;


/*  public  ContinueSFTPService(String username, String password, String host, int port) throws JSchException {//port=22
     this.username = username;
     this.password = password;
     this.privateKey = "";
     this.host = host;
     this.port = port;
     login(this.username,this.password,this.host,this.port,"");
  }*/


 /* *
  public ContinueSFTPService(String username, String host, int port, String privateKey) {

    this.username = username;

    this.host = host;

    this.port = port;

    this.privateKey = privateKey;

  }*/




  /**

   * 连接sftp服务器

   */

  public void login(String username,String password,String host,int port,String privateKey){

    try {

      JSch jsch = new JSch();


      session = jsch.getSession(username, host, port);

      if (password != null) {

        session.setPassword(password);

      }

      session.setTimeout(100000);



      Properties config = new Properties();

      config.put("StrictHostKeyChecking", "no");

      session.setConfig(config);

      session.connect();



      Channel channel = session.openChannel(Type);

      channel.connect();

      this.sftp = (ChannelSftp) channel;

    } catch (JSchException e) {

      e.printStackTrace();

    }

  }

  /**

   * 关闭连接 server

   */

  public void logout(){

    if (sftp != null) {

      if (sftp.isConnected()) {

        sftp.disconnect();

      }

    }

    if (session != null) {

      if (session.isConnected()) {

        session.disconnect();

      }

    }

  }

  /**

   * 将输入流的数据上传到sftp作为文件。

   * @param directory  上传到该目录

   * @param sftpFileName  sftp端文件名

   * @param input   输入流

   */

  public void upload(String directory, String sftpFileName, InputStream input) throws SftpException{

    try{
      sftp.cd(directory);
      sftp.put(input, sftpFileName);  //上传文件
    }catch (Exception e){
      log.error("文件上传失败");
    }
  }



  /**

   * 下载文件。

   * @param directory 下载目录

   * @param downloadFile 下载的文件

   * @param saveFile 存在本地的路径

   */

  public void download(String directory, String downloadFile, String saveFile) throws SftpException, FileNotFoundException{

    if (directory != null && !"".equals(directory)) {

      sftp.cd(directory);

    }

    File file = new File(saveFile);

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

  }

  /**

   * 下载文件

   * @param directory 下载目录

   * @param downloadFile 下载的文件名

   * @return 字节数组

   */

  public InputStream download(String directory, String downloadFile) throws SftpException, IOException{

    if (directory != null && !"".equals(directory)) {

      sftp.cd(directory);

    }

    InputStream is = sftp.get(downloadFile);



    //byte[] fileData = IOUtils.toByteArray(is);



    //return fileData;
    return is;
  }

  /**

   * 删除文件

   * @param directory 要删除文件所在目录

   * @param deleteFile 要删除的文件

   */

  public Boolean delete(String directory, String deleteFile){

    try {
      sftp.cd(directory);

      sftp.rm(deleteFile);

    }catch (Exception e){
      e.printStackTrace();
      return false;
    }

    return true;
  }

  /**

   * 列出目录下的文件
   * @param directory 要列出的目录
   * @return


   */

  public ArrayList<ChannelSftp.LsEntry> listFiles(String directory) throws SftpException {
    ArrayList<ChannelSftp.LsEntry> files = new ArrayList<>();
    sftp.cd(directory);
    Vector lss = sftp.ls("*");
    for (int i = 0; i < lss.size(); i++)
    {
      Object obj = lss.elementAt(i);
      if (obj instanceof com.jcraft.jsch.ChannelSftp.LsEntry)
      {
        ChannelSftp.LsEntry entry = (ChannelSftp.LsEntry) obj;
        if (true && !entry.getAttrs().isDir())
        {
          files.add(entry);
        }
        if (true && entry.getAttrs().isDir())
        {
          if (!entry.getFilename().equals(".") && !entry.getFilename().equals(".."))
          {
            files.add(entry);
          }
        }
      }
    }
    return files;

  }
  public static void main (String[] args) {
    try {
      //String username, String password, String host, int port
      /*ContinueSFTPService continueSFTPService=new ContinueSFTPService("root","Jydl*3377","192.168.9.103",22);

      //login("root","Jydl*3377","192.168.9.103",22);
      System.out.println("连接成功");
      ArrayList<ChannelSftp.LsEntry> ftpFileArr = continueSFTPService.listFiles(File.separator+"usr");
      for (int ii = 0; ii < ftpFileArr.size(); ii++) {
        System.out.println("name == "+ ftpFileArr.get(ii).getFilename());
        System.out.println("attrs"+ftpFileArr.get(ii).getAttrs());
        System.out.println("Longname"+ftpFileArr.get(ii).getLongname());
      }
      continueSFTPService.logout();
      System.out.println("连接已断开");*/
    }catch (Exception e){
      System.out.println("连接失败"+e);
    }

  }



}
