package com.jiayue.ipfcst.ftpsftp.service;

import java.io.*;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.SocketException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

@Service
@Slf4j
public class ContinueFTPService {
  public FTPClient client;

  /*public ContinueFTPService(String host,int port ,String username,  String password) throws IOException {
    initFtpClient(host, port, username, password);
  }
  public ContinueFTPService(String host, String userName, String password)
    throws SocketException, IOException {
    initFtpClient(host, 21, userName, password);
  }*/

  /**
   * 登录
   * @param host
   * @param port
   * @param userName
   * @param password
   * @throws IOException
   */
  public void initFtpClient(String host, int port, String userName,
                            String password) throws IOException {

    client =new FTPClient();//s生成一个新的client
    client.connect(host,port);//链接
    client.login(userName,password);//通过用户名和密码登录

  }

  /**
   * 得到所有目录
   * @param remotepath
   * @return
   */
  public FTPFile[] listFiles(String remotepath) throws IOException {
    client.enterLocalPassiveMode();
    remotepath = new String(remotepath.getBytes(StandardCharsets.UTF_8),"iso-8859-1");
    if (client == null){
      return null;
    }
    client.changeWorkingDirectory(remotepath);//获取所有的目录
    return client.listFiles();//返回获取到的目录信息
  }

  /**
   * 上传
   * @param remotepath（ftp的路径）
   * @return上传是否成功
   * @throws FileNotFoundException
   */
  public boolean upload(String remotepath,String filename,InputStream inputStream) throws IOException {
    if (null == client){//如果获取到的信息为空则返回false
      return false;
    }
    boolean res = false;
    client.setFileType(FTPClient.BINARY_FILE_TYPE);//设置上传文件的类型
    client.changeWorkingDirectory(remotepath);//获取上传的路径地址
    String charSet = System.getProperties().get("file.encoding").toString();
    String name = new String(filename.getBytes(charSet),"ISO-8859-1");
    res=client.storeFile(name,inputStream);
    return res;
  }

  /**
   * 下载
   * @param name 文件名称
   * @return 下载是否成功
   */
  public InputStream downLoad(String name) throws IOException {
    InputStream ins = null;

    try {
      client.setFileType(FTPClient.BINARY_FILE_TYPE);//设置下载文件的类型
      //获取系统字符集
      String charSet = System.getProperties().get("file.encoding").toString();
      String fileName = new String(name.getBytes(charSet),"ISO-8859-1");
      ins = client.retrieveFileStream(fileName);
    }catch (Exception e){
      log.error("FTP下载错误");
    }
    return ins;
  }

  /**
   * 删除文件
   * @param remotepath ftp服务端路径
   * @return
   */
  public boolean delete(String remotepath,String name) throws IOException {
    client.changeWorkingDirectory(remotepath);
    String charSet = System.getProperties().get("file.encoding").toString();
    String fileName = new String(name.getBytes(charSet),"ISO-8859-1");
    return  client.deleteFile(remotepath+fileName);//删除文件是否成功
  }

  /**
   * 创建目录
   * @param remotepath ftp服务端路径
   * @return
   */
  public boolean makeDirectory(String remotepath) throws IOException {
    boolean res = false;

    if (null == client){
      return res;
    }

    String[] item = remotepath.split("/");//以‘/’分割成字符串数组
    String currentPath="";
    for (int i = 0; i <item.length-1 ; i++) {

      currentPath = currentPath +"/"+item[i];//创建目录
      client.makeDirectory(currentPath);
    }
    return client.makeDirectory(remotepath);
  }

  /**
   * 删除文件
   * @param remotepath ftp端路径
   * @return
   */
  private boolean deleteDirectory(String remotepath) throws IOException {
    boolean res= false;
    FTPFile[] files= listFiles(remotepath);//获取文件数组
    for (int i = 0; i <files.length ; i++) {
      if (files[i].isDirectory()){ //如果是删除目录
        deleteDirectory(remotepath+"/"+files[i].getName());//删除目录
      }else {
        client.deleteFile(remotepath+"/"+files[i].getName());//删除文件
      }

    }
    return client.removeDirectory(remotepath);
  }

  /**
   * 重命名
   * @param remoteOldPath ftp旧名字文件
   * @param remoteNewPath ftp新名字文件
   * @return 是否修改名字成功
   */
  public boolean replaceName(String remoteOldPath,String remoteNewPath) throws IOException {

    if (null == client){
      return false;
    }
    return client.rename(remoteOldPath,remoteNewPath);
  }

  /**
   * 退出登录
   * @throws IOException
   */
  public void close() throws IOException {
    if (null != client)
      client.logout();
  }

  public static void main (String[] args) {
    try {

      //ContinueFTPService ft = new ContinueFTPService("43.254.3.182", 21, "syjy", "^YHN7ujm");
      //   System.out.print( ft.upload("D:\\7za.exe","/ftp"));
      System.out.println("连接成功");
      //FTPFile[] files = ft.listFiles("/");

      //System.out.println(ft.upload("/Users/wanghongchen/Desktop/test.txt","/"));
      /*for (int i = 0; i < files.length; i++) {
        String name = new String(files[i].getName().getBytes("iso-8859-1"),"UTF-8");
        System.out.println("内容有：" + name);
      }*/
      //ft.close();
    }catch (Exception e){
      System.out.println("连接失败"+e);
    }
    //System.out.println("删除文件："+ft.delete("222.png"));
  }


}
