package com.ann.demo.utils;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * @Author: LeiJiaXin
 * @Date: 2019/8/22 9:17
 */
public class FTPUtil {

    static final Logger logger = LoggerFactory.getLogger(FTPUtil.class);

    /**
     * 连接 FTP 服务器
     *
     * @param addr     FTP 服务器 IP 地址
     * @param port     FTP 服务器端口号
     * @param username 登录用户名
     * @param password 登录密码
     * @return
     * @throws Exception
     */
    public static FTPClient connectFtpServer(String addr, int port, String username, String password) throws Exception {
        FTPClient ftpClient = new FTPClient();
        try {
            ftpClient.setControlEncoding("gbk");

            ftpClient.connect(addr, port);
            /**登录 FTP 服务器
             * 1）如果传入的账号为空，则使用匿名登录，此时账号使用 "Anonymous"，密码为空即可*/
            if (StringUtils.isBlank(username)) {
                ftpClient.login("Anonymous", "");
            } else {
                ftpClient.login(username, password);
            }

            /** 设置传输的文件类型
             * BINARY_FILE_TYPE：二进制文件类型
             * ASCII_FILE_TYPE：ASCII传输方式，这是默认的方式
             * ....
             */
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);

            /**
             * 确认应答状态码是否正确完成响应
             * 凡是 2开头的 isPositiveCompletion 都会返回 true，因为它底层判断是：
             * return (reply >= 200 && reply < 300);
             */
            int reply = ftpClient.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                /**
                 * 如果 FTP 服务器响应错误 中断传输、断开连接
                 * abort：中断文件正在进行的文件传输，成功时返回 true,否则返回 false
                 * disconnect：断开与服务器的连接，并恢复默认参数值
                 */
                ftpClient.abort();
                ftpClient.disconnect();
            }
        } catch (IOException e) {
            throw e;
        }
        return ftpClient;
    }

    /**
     * 使用完毕，应该及时关闭连接
     * 终止 ftp 传输
     * 断开 ftp 连接
     *
     * @param ftpClient
     * @return
     */
    public static FTPClient closeFTPConnect(FTPClient ftpClient) throws Exception {
        try {
            if (ftpClient != null && ftpClient.isConnected()) {
                ftpClient.abort();
                ftpClient.disconnect();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ftpClient;
    }


    public static boolean downloadFtp(String path, FTPClient ftp, File file) throws Exception {
        InputStream is = null;
        FileOutputStream fos = null;
        boolean result = false;
        try {
            is = ftp.retrieveFileStream(path);
            if(is != null){
                byte[] bytes = new byte[1024];
                int i;
                fos = new FileOutputStream(file);
                while ((i = is.read(bytes)) != -1) {
                    fos.write(bytes, 0, i);
                }
                closeFTPConnect(ftp);
            }
            if(file.length() == 0){
                FileUtils.deleteImageFile(file);
            }else{
                result = true;
            }
        } catch (Exception e) {
            FileUtils.deleteImageFile(file);
            throw e;
        } finally {
            try {
                if (fos != null) {
                    fos.close();
                }
                if (is != null) {
                    is.close();
                }
            } catch (IOException e) {
                FileUtils.deleteImageFile(file);
                throw e;
            }
        }
        return result;
    }

    public static boolean deleteFile(String address) throws Exception {
        boolean flag = false;
        FTPClient ftpClient = null;
        try {
            String url = "";
            String path = "";
            Integer port = 21;
            // 处理 “/”
            if (address.indexOf("/") == -1) {
                address = address.replace("\\", "/");
            }
            address = address.substring(address.indexOf("/") + 2, address.length());
            path = address.substring(address.indexOf("/"), address.length());
            url = address.substring(0, address.indexOf("/"));

            ftpClient = connectFtpServer(url, port, "his", "his_docus");
            // 切换FTP目录
            ftpClient.changeWorkingDirectory("/");
            int dele = ftpClient.dele(path);
            logger.error("删除FTP文件为：{}",address);
            flag = true;
        } catch (Exception e) {
           throw e;
        } finally {
            if (ftpClient != null && ftpClient.isConnected()) {
                try {
                    ftpClient.disconnect();// 断开连接，如果想连续删除就得把finally块注掉
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return flag;
    }


    public static void main(String[] args) throws Exception {
       /* String address = "ftp://10.6.0.241/02019-08-29.png;ftp://10.6.0.241/12019-08-29.png";
        File imageFile = FileUtils.createFile("images","2019","0827", "阿雷小猴子" );
        File pdfFile = FileUtils.createFile("pdfs","2019","0827", "阿雷小猴子" );
        String s = DownloadUtils.downloadImageFiles(address, imageFile.getParent());
        //  图片那么转成pdf
        String pdfPath = PdfUtils.imageDirToPdf(s,pdfFile);
        System.out.println(pdfPath);*/
    }
}
